diff --git a/datasource.js b/datasource.js index e599e1ca..c2b68147 100644 --- a/datasource.js +++ b/datasource.js @@ -30,13 +30,16 @@ import { DebitAccessFixes1726685229264 } from './build/src/services/storage/migr import { DebitToPub1727105758354 } from './build/src/services/storage/migrations/1727105758354-debit_to_pub.js' import { 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, ManagementGrant], // synchronize: true, }) -//npx typeorm migration:generate ./src/services/storage/migrations/management_grant -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 14264ba5..a1f745cd 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.1.4", + "@shocknet/clink-sdk": "^1.1.6", "@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.1.4", - "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.4.tgz", - "integrity": "sha512-b0YVsisIkTxOAwxrb1a9DGDxwWkHm7kJ2BpqOzkEbtJ6flkJxo2ggmRH3fxsVIiJOeVWwgSPATab68JU8DSLOA==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@shocknet/clink-sdk/-/clink-sdk-1.1.6.tgz", + "integrity": "sha512-PXNXdaS5sFIgfdWV5yMW0/ghrORAEVTy9K3fY4j/Rf4fjbNspBAaDioYn7to+lU/boPUxRMmFE0ix/2Mr6pkFQ==", "license": "ISC", "dependencies": { "@noble/hashes": "^1.8.0", diff --git a/package.json b/package.json index 9894c250..c3ea45d3 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.1.4", + "@shocknet/clink-sdk": "^1.1.6", "@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..bacdf85c 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 @@ -418,6 +433,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 +587,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 +647,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__ @@ -1216,6 +1252,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 +1330,19 @@ 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)_ + ### MetricsFile ### MigrationUpdate diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index bd9a32f0..3971791f 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) @@ -397,6 +400,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 +938,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 +1102,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() diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index 9a1b63ff..4f797f59 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,19 @@ 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 MetricsFile struct { } type MigrationUpdate struct { diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index 8e6e04f2..b7b4a73f 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' ) @@ -1116,6 +1160,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} diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 5750aa3e..615265f4 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() diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index a08f4015..569c5842 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') diff --git a/proto/autogenerated/ts/nostr_transport.ts b/proto/autogenerated/ts/nostr_transport.ts index 5e9ea211..e7e93016 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') @@ -728,6 +766,19 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { }}) }catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e } 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 +850,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') diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 9dc61dbd..21d59051 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 | 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 | 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' } @@ -320,6 +329,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 +350,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 +358,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 @@ -2011,6 +2023,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 +2505,86 @@ 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 MetricsFile = { } export const MetricsFileOptionalFields: [] = [] diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 21f0a9d6..19f914da 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -592,12 +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 AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){ option (auth_type) = "User"; option (http_method) = "post"; option (http_route) = "/api/user/debit/authorize"; option (nostr) = true; } + rpc AuthorizeManage(structs.ManageAuthorizationRequest) returns (structs.ManageAuthorization){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/manage/authorize"; + option (nostr) = true; + } rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){ option (auth_type) = "User"; option (http_method) = "post"; @@ -628,6 +640,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..3b1f0d8f 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -674,6 +674,22 @@ message DebitAuthorizationRequest { optional string request_id = 3; } +message ManageAuthorizationRequest { + string authorize_npub = 1; + optional string request_id = 2; + bool ban = 3; +} + +message ManageAuthorization { + string manage_id = 1; + bool authorized = 2; + string npub = 3; +} + +message ManageAuthorizations { + repeated ManageAuthorization manages = 1; +} + message DebitAuthorization { string debit_id = 1; bool authorized = 2; @@ -718,6 +734,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/services/main/managementManager.ts b/src/services/main/managementManager.ts index 26bf6b4d..2f31254e 100644 --- a/src/services/main/managementManager.ts +++ b/src/services/main/managementManager.ts @@ -7,14 +7,15 @@ 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 } from "@shocknet/clink-sdk"; +import { nofferEncode, OfferPointer, OfferPriceType, NmanageRequest, NmanageResponse, NmanageCreateOffer, NmanageUpdateOffer, NmanageDeleteOffer, NmanageGetOffer, NmanageListOffers, OfferData, OfferFields, NmanageFailure } from "@shocknet/clink-sdk"; import { UnsignedEvent } from "nostr-tools"; -type Result = { success: true, result: T } | { success: false, error: string, code: number } +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 = {} constructor(storage: Storage, settings: MainSettings) { this.storage = storage; @@ -25,19 +26,62 @@ export class ManagementManager { this.nostrSend = f } - public async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { + 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) + 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, { requestId, npub }: { requestId: string, npub: string }) => { + const message: Types.LiveManageRequest & { requestId: string, status: 'OK' } = { requestId: "GetLiveManageRequests", status: 'OK', npub: npub, request_id: requestId } + this.nostrSend({ type: 'app', appId: appId }, { type: 'content', content: JSON.stringify(message), pub: npub }) + } + + private sendError(event: NostrEvent, err: NmanageFailure) { + const e = newNmanageResponse(JSON.stringify(err), event) + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + } + + private handleAuthRequired(nmanageReq: NmanageRequest, event: NostrEvent) { + if (this.awaitingRequests[event.pub]) { + this.sendError(event, { res: 'GFY', code: 4, error: 'Rate Limited', retry_after: 60 * 10 }) + return + } + this.awaitingRequests[event.pub] = { request: nmanageReq, event } + this.sendManageAuthorizationRequest(event.appId, { requestId: event.id, npub: event.pub }) + } + + + + async handleRequest(nmanageReq: NmanageRequest, event: NostrEvent): Promise { try { const r = await this.doNmanage(nmanageReq, event) - let e: UnsignedEvent - if (!r.success) { - e = newNmanageResponse(JSON.stringify({ code: r.code, error: codeToMessage(r.code) }), event) - } else { - e = newNmanageResponse(JSON.stringify(r.result), event) + if (r.state === 'authRequired') { + this.handleAuthRequired(nmanageReq, event) + return } + if (r.state === 'error') { + this.sendError(event, r.err) + return + } + const e = newNmanageResponse(JSON.stringify(r.result), event) this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) } catch (err) { - const e = newNmanageResponse(JSON.stringify({ code: 2, error: codeToMessage(2) }), event) - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + this.sendError(event, { res: 'GFY', code: 2, error: 'Temporary Failure' }) } } @@ -60,7 +104,7 @@ export class ManagementManager { const listResult = await this.listOffers(nmanageReq, event.pub); return this.getNmanageResponse(event.appId, listResult) default: - return { success: false, error: `Unknown action: ${action}`, code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: `Request Denied: Unknown action: ${action}` } } } } @@ -83,23 +127,23 @@ export class ManagementManager { } private async getNmanageResponse(appId: string, result: Result): Promise> { - if (!result.success) { + if (result.state !== 'success') { return result } const args = result.result const app = await this.storage.applicationStorage.GetApplication(appId) if (args && Array.isArray(args)) { return { - success: true, result: { + state: 'success', result: { res: 'ok', resource: 'offer', details: args.map(offer => this.getOfferData(offer, app.nostr_public_key!)) } } } if (!args) { - return { success: true, result: { res: 'ok', resource: 'offer' } } + return { state: 'success', result: { res: 'ok', resource: 'offer' } } } return { - success: true, result: { + state: 'success', result: { res: 'ok', resource: 'offer', details: this.getOfferData(args, app.nostr_public_key!) } } @@ -107,53 +151,53 @@ export class ManagementManager { private async getOffer(nmanageReq: NmanageGetOffer, requestorPub: string): Promise> { const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offer.success) { + if (offer.state !== 'success') { return offer } - return { success: true, result: offer.result } + return { state: 'success', result: offer.result } } private async listOffers(nmanageReq: NmanageListOffers, requestorPub: string): Promise> { const appUserId = nmanageReq.pointer if (!appUserId) { - return { success: false, error: 'No pointer provided', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } } const grantResult = await this.validateGrantAccess(appUserId, requestorPub) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } const offers = await this.storage.offerStorage.getManagedUserOffers(appUserId, requestorPub) - return { success: true, result: offers } + return { state: 'success', result: offers } } private validateOfferFields(fields: OfferFields): Result { if (!fields.label || typeof fields.label !== 'string') { - return { success: false, error: 'Label is required', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'label' } } } if (fields.price_sats && typeof fields.price_sats !== 'number') { - return { success: false, error: 'Price must be a number', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'price_sats' } } } if (fields.callback_url && typeof fields.callback_url !== 'string') { - return { success: false, error: 'Callback URL must be a string', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'callback_url' } } } if (fields.payer_data && !Array.isArray(fields.payer_data)) { - return { success: false, error: 'Payer data must be an array', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } } - return { success: true, result: undefined } + return { state: 'success', result: undefined } } private async createOffer(nmanageReq: NmanageCreateOffer): Promise> { const appUserId = nmanageReq.pointer if (!appUserId) { - return { success: false, error: 'No pointer provided', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: No pointer provided' } } } const grantResult = await this.validateGrantAccess(appUserId, appUserId) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } const validateResult = this.validateOfferFields(nmanageReq.offer.fields) - if (!validateResult.success) { + if (validateResult.state !== 'success') { return validateResult } const dataMap: Record = {} @@ -166,51 +210,56 @@ export class ManagementManager { price_sats: nmanageReq.offer.fields.price_sats, expected_data: dataMap, }) - return { success: true, result: offer } + return { state: 'success', result: offer } } private async validateGrantAccess(appUserId: string, requestorPub: string): Promise> { const grant = await this.storage.managementStorage.getGrant(appUserId, requestorPub) if (!grant) { - // TODO request from user - return { success: false, error: 'No grant found', code: 1 } + return { state: 'authRequired' } } - if (grant.expires_at_unix < Date.now()) { - return { success: false, error: 'Grant expired', code: 3 } + if (grant.expires_at_unix > 0 && grant.expires_at_unix < Date.now()) { + return { state: 'authRequired' } } - return { success: true, result: undefined } + + if (grant.banned) { + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App is banned' } } + } + + + return { state: 'success', result: undefined } } private async validateOfferAccess(offerId: string, requestorPub: string): Promise> { const offer = await this.storage.offerStorage.GetOffer(offerId) if (!offer) { - return { success: false, error: 'Offer not found', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: Offer not found' } } } if (offer.management_pubkey !== requestorPub) { - return { success: false, error: 'App not authorized to update offer', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 1, error: 'Request Denied: App not authorized to update offer' } } } const grantResult = await this.validateGrantAccess(offer.app_user_id, requestorPub) - if (!grantResult.success) { + if (grantResult.state !== 'success') { return grantResult } - return { success: true, result: offer } + return { state: 'success', result: offer } } private async updateOffer(nmanageReq: NmanageUpdateOffer, requestorPub: string): Promise> { const offer = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offer.success) { + if (offer.state !== 'success') { return offer } const validateResult = this.validateOfferFields(nmanageReq.offer.fields) - if (!validateResult.success) { + if (validateResult.state !== 'success') { return validateResult } const dataMap: Record = {} for (const data of nmanageReq.offer.fields.payer_data || []) { if (typeof data !== 'string') { - return { success: false, error: 'Payer data must be a string', code: 1 } + return { state: 'error', err: { res: 'GFY', code: 5, error: 'Invalid Field/Value', field: 'payer_data' } } } dataMap[data] = Types.OfferDataType.DATA_STRING } @@ -222,18 +271,18 @@ export class ManagementManager { }) const updatedOffer = await this.storage.offerStorage.GetOffer(nmanageReq.offer.id) if (!updatedOffer) { - return { success: false, error: 'Offer not found', code: 2 } + return { state: 'error', err: { res: 'GFY', code: 2, error: 'Temporary Failure: Offer not found' } } } - return { success: true, result: updatedOffer } + return { state: 'success', result: updatedOffer } } private async deleteOffer(nmanageReq: NmanageDeleteOffer, requestorPub: string): Promise> { const offerResult = await this.validateOfferAccess(nmanageReq.offer.id, requestorPub) - if (!offerResult.success) { + if (offerResult.state !== 'success') { return offerResult } await this.storage.offerStorage.DeleteUserOffer(offerResult.result.app_user_id, offerResult.result.offer_id) - return { success: true, result: undefined } + return { state: 'success', result: undefined } } } diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index 5e204369..b33c2202 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,12 @@ 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) + }, BanDebit: async ({ ctx, req }) => { const err = Types.DebitOperationValidate(req, { npub_CustomCheck: pub => pub !== '', diff --git a/src/services/storage/entity/ManagementGrant.ts b/src/services/storage/entity/ManagementGrant.ts index 46a962cd..1ce4650d 100644 --- a/src/services/storage/entity/ManagementGrant.ts +++ b/src/services/storage/entity/ManagementGrant.ts @@ -15,6 +15,9 @@ export class ManagementGrant { @Column() expires_at_unix: number + @Column() + banned: boolean + @CreateDateColumn() created_at: Date diff --git a/src/services/storage/managementStorage.ts b/src/services/storage/managementStorage.ts index 6ff5a8b0..092ecdd4 100644 --- a/src/services/storage/managementStorage.ts +++ b/src/services/storage/managementStorage.ts @@ -11,7 +11,11 @@ export class ManagementStorage { return this.dbs.FindOne('ManagementGrant', { where: { app_pubkey: appPubkey, app_user_id: appUserId } }); } - async addGrant(appUserId: string, appPubkey: string, expires_at_unix: number) { - return this.dbs.CreateAndSave('ManagementGrant', { app_user_id: appUserId, app_pubkey: appPubkey, expires_at_unix }); + 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 } }); } } \ No newline at end of file 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"`); + } + +}