diff --git a/package.json b/package.json index b86d0558..a816c25a 100644 --- a/package.json +++ b/package.json @@ -82,4 +82,4 @@ "ts-node": "10.7.0", "typescript": "5.5.4" } -} +} \ No newline at end of file diff --git a/proto/autogenerated/client.md b/proto/autogenerated/client.md index 8aa85f07..3e3eaca3 100644 --- a/proto/autogenerated/client.md +++ b/proto/autogenerated/client.md @@ -200,6 +200,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 +- RespondToDebit + - auth type: __User__ + - input: [DebitResponse](#DebitResponse) + - This methods has an __empty__ __response__ body + - UpdateCallbackUrl - auth type: __User__ - input: [CallbackUrl](#CallbackUrl) @@ -636,6 +641,13 @@ The nostr server will send back a message response, and inside the body there wi - input: [RequestNPubLinkingTokenRequest](#RequestNPubLinkingTokenRequest) - output: [RequestNPubLinkingTokenResponse](#RequestNPubLinkingTokenResponse) +- RespondToDebit + - auth type: __User__ + - http method: __post__ + - http route: __/api/user/debit/finish__ + - input: [DebitResponse](#DebitResponse) + - This methods has an __empty__ __response__ body + - SendAppUserToAppPayment - auth type: __App__ - http method: __post__ @@ -797,6 +809,7 @@ The nostr server will send back a message response, and inside the body there wi ### DebitAuthorizationRequest - __authorize_npub__: _string_ + - __request_id__: _string_ *this field is optional - __rules__: ARRAY of: _[DebitRule](#DebitRule)_ ### DebitAuthorizations @@ -808,6 +821,11 @@ The nostr server will send back a message response, and inside the body there wi ### DebitOperation - __npub__: _string_ +### DebitResponse + - __npub__: _string_ + - __request_id__: _string_ + - __response__: _[DebitResponse_response](#DebitResponse_response)_ + ### DebitRule - __rule__: _[DebitRule_rule](#DebitRule_rule)_ @@ -885,6 +903,7 @@ The nostr server will send back a message response, and inside the body there wi ### LiveDebitRequest - __debit__: _[LiveDebitRequest_debit](#LiveDebitRequest_debit)_ - __npub__: _string_ + - __request_id__: _string_ ### LiveUserOperation - __operation__: _[UserOperation](#UserOperation)_ diff --git a/proto/autogenerated/go/http_client.go b/proto/autogenerated/go/http_client.go index 1177a478..446d5e7a 100644 --- a/proto/autogenerated/go/http_client.go +++ b/proto/autogenerated/go/http_client.go @@ -107,6 +107,7 @@ type Client struct { RequestNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) ResetDebit func(req DebitOperation) error ResetNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error) + RespondToDebit func(req DebitResponse) error SendAppUserToAppPayment func(req SendAppUserToAppPaymentRequest) error SendAppUserToAppUserPayment func(req SendAppUserToAppUserPaymentRequest) error SetMockAppBalance func(req SetMockAppBalanceRequest) error @@ -1433,6 +1434,30 @@ func NewClient(params ClientParams) *Client { } return &res, nil }, + RespondToDebit: func(req DebitResponse) error { + auth, err := params.RetrieveUserAuth() + if err != nil { + return err + } + finalRoute := "/api/user/debit/finish" + 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 + }, SendAppUserToAppPayment: func(req SendAppUserToAppPaymentRequest) error { auth, err := params.RetrieveAppAuth() if err != nil { diff --git a/proto/autogenerated/go/types.go b/proto/autogenerated/go/types.go index cb884762..7769ada6 100644 --- a/proto/autogenerated/go/types.go +++ b/proto/autogenerated/go/types.go @@ -175,6 +175,7 @@ type DebitAuthorization struct { } type DebitAuthorizationRequest struct { Authorize_npub string `json:"authorize_npub"` + Request_id string `json:"request_id"` Rules []DebitRule `json:"rules"` } type DebitAuthorizations struct { @@ -186,6 +187,11 @@ type DebitExpirationRule struct { type DebitOperation struct { Npub string `json:"npub"` } +type DebitResponse struct { + Npub string `json:"npub"` + Request_id string `json:"request_id"` + Response *DebitResponse_response `json:"response"` +} type DebitRule struct { Rule *DebitRule_rule `json:"rule"` } @@ -261,8 +267,9 @@ type LinkNPubThroughTokenRequest struct { Token string `json:"token"` } type LiveDebitRequest struct { - Debit *LiveDebitRequest_debit `json:"debit"` - Npub string `json:"npub"` + Debit *LiveDebitRequest_debit `json:"debit"` + Npub string `json:"npub"` + Request_id string `json:"request_id"` } type LiveUserOperation struct { Operation *UserOperation `json:"operation"` @@ -497,6 +504,18 @@ type UsersInfo struct { No_balance int64 `json:"no_balance"` Total int64 `json:"total"` } +type DebitResponse_response_type string + +const ( + DENIED DebitResponse_response_type = "denied" + INVOICE DebitResponse_response_type = "invoice" +) + +type DebitResponse_response struct { + Type DebitResponse_response_type `json:"type"` + Denied *Empty `json:"denied"` + Invoice *string `json:"invoice"` +} type DebitRule_rule_type string const ( diff --git a/proto/autogenerated/ts/express_server.ts b/proto/autogenerated/ts/express_server.ts index 050396bc..997d3719 100644 --- a/proto/autogenerated/ts/express_server.ts +++ b/proto/autogenerated/ts/express_server.ts @@ -481,6 +481,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'RespondToDebit': + if (!methods.RespondToDebit) { + throw new Error('method RespondToDebit not found' ) + } else { + const error = Types.DebitResponseValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.RespondToDebit({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'UpdateCallbackUrl': if (!methods.UpdateCallbackUrl) { throw new Error('method UpdateCallbackUrl not found' ) @@ -1323,6 +1335,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.RespondToDebit) throw new Error('method: RespondToDebit is not implemented') + app.post('/api/user/debit/finish', async (req, res) => { + const info: Types.RequestInfo = { rpcName: 'RespondToDebit', 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.RespondToDebit) throw new Error('method: RespondToDebit 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.DebitResponseValidate(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.RespondToDebit({rpcName:'RespondToDebit', 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.SendAppUserToAppPayment) throw new Error('method: SendAppUserToAppPayment is not implemented') app.post('/api/app/internal/pay', async (req, res) => { const info: Types.RequestInfo = { rpcName: 'SendAppUserToAppPayment', batch: false, nostr: false, batchSize: 0} diff --git a/proto/autogenerated/ts/http_client.ts b/proto/autogenerated/ts/http_client.ts index 2b2fbe6a..56f06543 100644 --- a/proto/autogenerated/ts/http_client.ts +++ b/proto/autogenerated/ts/http_client.ts @@ -691,6 +691,17 @@ export default (params: ClientParams) => ({ } return { status: 'ERROR', reason: 'invalid response' } }, + RespondToDebit: async (request: Types.DebitResponse): Promise => { + const auth = await params.retrieveUserAuth() + if (auth === null) throw new Error('retrieveUserAuth() returned null') + let finalRoute = '/api/user/debit/finish' + 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' } + }, SendAppUserToAppPayment: async (request: Types.SendAppUserToAppPaymentRequest): Promise => { const auth = await params.retrieveAppAuth() if (auth === null) throw new Error('retrieveAppAuth() returned null') diff --git a/proto/autogenerated/ts/nostr_client.ts b/proto/autogenerated/ts/nostr_client.ts index 20085352..10a7141f 100644 --- a/proto/autogenerated/ts/nostr_client.ts +++ b/proto/autogenerated/ts/nostr_client.ts @@ -540,6 +540,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ } return { status: 'ERROR', reason: 'invalid response' } }, + RespondToDebit: async (request: Types.DebitResponse): 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:'RespondToDebit',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' } + }, UpdateCallbackUrl: async (request: Types.CallbackUrl): 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 e7a00622..4b38912a 100644 --- a/proto/autogenerated/ts/nostr_transport.ts +++ b/proto/autogenerated/ts/nostr_transport.ts @@ -375,6 +375,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => { callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) } break + case 'RespondToDebit': + if (!methods.RespondToDebit) { + throw new Error('method not defined: RespondToDebit') + } else { + const error = Types.DebitResponseValidate(operation.req) + opStats.validate = process.hrtime.bigint() + if (error !== null) throw error + await methods.RespondToDebit({...operation, ctx}); responses.push({ status: 'OK' }) + opStats.handle = process.hrtime.bigint() + callsMetrics.push({ ...opInfo, ...opStats, ...ctx }) + } + break case 'UpdateCallbackUrl': if (!methods.UpdateCallbackUrl) { throw new Error('method not defined: UpdateCallbackUrl') @@ -848,6 +860,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 'RespondToDebit': + try { + if (!methods.RespondToDebit) throw new Error('method: RespondToDebit 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.DebitResponseValidate(request) + stats.validate = process.hrtime.bigint() + if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback) + await methods.RespondToDebit({rpcName:'RespondToDebit', 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 'UpdateCallbackUrl': try { if (!methods.UpdateCallbackUrl) throw new Error('method: UpdateCallbackUrl is not implemented') diff --git a/proto/autogenerated/ts/types.ts b/proto/autogenerated/ts/types.ts index 481a77de..b3de5706 100644 --- a/proto/autogenerated/ts/types.ts +++ b/proto/autogenerated/ts/types.ts @@ -34,8 +34,8 @@ export type UserContext = { app_user_id: string user_id: string } -export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input -export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output +export type UserMethodInputs = AddProduct_Input | AuthorizeDebit_Input | BanDebit_Input | DecodeInvoice_Input | EditDebit_Input | EnrollAdminToken_Input | GetDebitAuthorizations_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | OpenChannel_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UserHealth_Input +export type UserMethodOutputs = AddProduct_Output | AuthorizeDebit_Output | BanDebit_Output | DecodeInvoice_Output | EditDebit_Output | EnrollAdminToken_Output | GetDebitAuthorizations_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | OpenChannel_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UserHealth_Output export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest} @@ -219,6 +219,9 @@ export type ResetDebit_Output = ResultError | { status: 'OK' } export type ResetNPubLinkingToken_Input = {rpcName:'ResetNPubLinkingToken', req: RequestNPubLinkingTokenRequest} export type ResetNPubLinkingToken_Output = ResultError | ({ status: 'OK' } & RequestNPubLinkingTokenResponse) +export type RespondToDebit_Input = {rpcName:'RespondToDebit', req: DebitResponse} +export type RespondToDebit_Output = ResultError | { status: 'OK' } + export type SendAppUserToAppPayment_Input = {rpcName:'SendAppUserToAppPayment', req: SendAppUserToAppPaymentRequest} export type SendAppUserToAppPayment_Output = ResultError | { status: 'OK' } @@ -296,6 +299,7 @@ export type ServerMethods = { RequestNPubLinkingToken?: (req: RequestNPubLinkingToken_Input & {ctx: AppContext }) => Promise ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise + RespondToDebit?: (req: RespondToDebit_Input & {ctx: UserContext }) => Promise SendAppUserToAppPayment?: (req: SendAppUserToAppPayment_Input & {ctx: AppContext }) => Promise SendAppUserToAppUserPayment?: (req: SendAppUserToAppUserPayment_Input & {ctx: AppContext }) => Promise SetMockAppBalance?: (req: SetMockAppBalance_Input & {ctx: AppContext }) => Promise @@ -925,12 +929,15 @@ export const DebitAuthorizationValidate = (o?: DebitAuthorization, opts: DebitAu export type DebitAuthorizationRequest = { authorize_npub: string + request_id?: string rules: DebitRule[] } -export const DebitAuthorizationRequestOptionalFields: [] = [] +export type DebitAuthorizationRequestOptionalField = 'request_id' +export const DebitAuthorizationRequestOptionalFields: DebitAuthorizationRequestOptionalField[] = ['request_id'] export type DebitAuthorizationRequestOptions = OptionsBaseMessage & { - checkOptionalsAreSet?: [] + checkOptionalsAreSet?: DebitAuthorizationRequestOptionalField[] authorize_npub_CustomCheck?: (v: string) => boolean + request_id_CustomCheck?: (v?: string) => boolean rules_ItemOptions?: DebitRuleOptions rules_CustomCheck?: (v: DebitRule[]) => boolean } @@ -941,6 +948,9 @@ export const DebitAuthorizationRequestValidate = (o?: DebitAuthorizationRequest, 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 ((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`) + if (!Array.isArray(o.rules)) return new Error(`${path}.rules: is not an array`) for (let index = 0; index < o.rules.length; index++) { const rulesErr = DebitRuleValidate(o.rules[index], opts.rules_ItemOptions, `${path}.rules[${index}]`) @@ -1010,6 +1020,35 @@ export const DebitOperationValidate = (o?: DebitOperation, opts: DebitOperationO return null } +export type DebitResponse = { + npub: string + request_id: string + response: DebitResponse_response +} +export const DebitResponseOptionalFields: [] = [] +export type DebitResponseOptions = OptionsBaseMessage & { + checkOptionalsAreSet?: [] + npub_CustomCheck?: (v: string) => boolean + request_id_CustomCheck?: (v: string) => boolean + response_Options?: DebitResponse_responseOptions +} +export const DebitResponseValidate = (o?: DebitResponse, opts: DebitResponseOptions = {}, path: string = 'DebitResponse::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`) + + const responseErr = DebitResponse_responseValidate(o.response, opts.response_Options, `${path}.response`) + if (responseErr !== null) return responseErr + + + return null +} + export type DebitRule = { rule: DebitRule_rule } @@ -1452,12 +1491,14 @@ export const LinkNPubThroughTokenRequestValidate = (o?: LinkNPubThroughTokenRequ export type LiveDebitRequest = { debit: LiveDebitRequest_debit npub: string + request_id: string } export const LiveDebitRequestOptionalFields: [] = [] export type LiveDebitRequestOptions = OptionsBaseMessage & { checkOptionalsAreSet?: [] debit_Options?: LiveDebitRequest_debitOptions npub_CustomCheck?: (v: string) => boolean + request_id_CustomCheck?: (v: string) => boolean } export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRequestOptions = {}, path: string = 'LiveDebitRequest::root.'): Error | null => { if (opts.checkOptionalsAreSet && opts.allOptionalsAreSet) return new Error(path + ': only one of checkOptionalsAreSet or allOptionalNonDefault can be set for each message') @@ -1470,6 +1511,9 @@ export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRe 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 } @@ -2826,6 +2870,42 @@ export const UsersInfoValidate = (o?: UsersInfo, opts: UsersInfoOptions = {}, pa return null } +export enum DebitResponse_response_type { + DENIED = 'denied', + INVOICE = 'invoice', +} +export const enumCheckDebitResponse_response_type = (e?: DebitResponse_response_type): boolean => { + for (const v in DebitResponse_response_type) if (e === v) return true + return false +} +export type DebitResponse_response = + {type:DebitResponse_response_type.DENIED, denied:Empty}| + {type:DebitResponse_response_type.INVOICE, invoice:string} + +export type DebitResponse_responseOptions = { + denied_Options?: EmptyOptions + invoice_CustomCheck?: (v: string) => boolean +} +export const DebitResponse_responseValidate = (o?: DebitResponse_response, opts:DebitResponse_responseOptions = {}, path: string = 'DebitResponse_response::root.'): Error | null => { + if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is null') + const stringType: string = o.type + switch (o.type) { + case DebitResponse_response_type.DENIED: + const deniedErr = EmptyValidate(o.denied, opts.denied_Options, `${path}.denied`) + if (deniedErr !== null) return deniedErr + + + break + case DebitResponse_response_type.INVOICE: + if (typeof o.invoice !== 'string') return new Error(`${path}.invoice: is not a string`) + if (opts.invoice_CustomCheck && !opts.invoice_CustomCheck(o.invoice)) return new Error(`${path}.invoice: custom check failed`) + + break + default: + return new Error(path + ': unknown type '+ stringType) + } + return null +} export enum DebitRule_rule_type { EXPIRATION_RULE = 'expiration_rule', FREQUENCY_RULE = 'frequency_rule', diff --git a/proto/service/methods.proto b/proto/service/methods.proto index 031ee20a..c86346b1 100644 --- a/proto/service/methods.proto +++ b/proto/service/methods.proto @@ -471,6 +471,12 @@ service LightningPub { option (http_route) = "/api/user/debit/reset"; option (nostr) = true; } + rpc RespondToDebit(structs.DebitResponse) returns (structs.Empty){ + option (auth_type) = "User"; + option (http_method) = "post"; + option (http_route) = "/api/user/debit/finish"; + option (nostr) = true; + } rpc GetLiveDebitRequests(structs.Empty) returns (stream structs.LiveDebitRequest){ option (auth_type) = "User"; option (http_method) = "post"; diff --git a/proto/service/structs.proto b/proto/service/structs.proto index ae2eca96..d3cbbbc6 100644 --- a/proto/service/structs.proto +++ b/proto/service/structs.proto @@ -493,6 +493,7 @@ message DebitOperation { message DebitAuthorizationRequest { string authorize_npub = 1; repeated DebitRule rules = 2; + optional string request_id = 3; } message DebitAuthorization { @@ -530,9 +531,19 @@ message DebitRule { } message LiveDebitRequest { - string npub = 1; + string request_id = 1; + string npub = 2; oneof debit { string invoice = 3; FrequencyRule frequency = 4; } +} + +message DebitResponse { + string request_id = 1; + string npub = 2; + oneof response { + Empty denied = 3; + string invoice = 4; + } } \ No newline at end of file diff --git a/src/nostrMiddleware.ts b/src/nostrMiddleware.ts index 11f8851b..20c5ca9b 100644 --- a/src/nostrMiddleware.ts +++ b/src/nostrMiddleware.ts @@ -52,7 +52,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett return } else if (event.kind === 21002) { const debitReq = j as NdebitData - mainHandler.handleNip68Debit(debitReq, event) + mainHandler.debitManager.handleNip68Debit(debitReq, event) return } if (!j.rpcName) { diff --git a/src/services/main/debitManager.ts b/src/services/main/debitManager.ts index d1e86b83..aa387611 100644 --- a/src/services/main/debitManager.ts +++ b/src/services/main/debitManager.ts @@ -8,6 +8,8 @@ import { DebitAccess, DebitAccessRules } from '../storage/entity/DebitAccess.js' import paymentManager from './paymentManager.js'; import { Application } from '../storage/entity/Application.js'; import { ApplicationUser } from '../storage/entity/ApplicationUser.js'; +import { NostrEvent, NostrSend, SendData, SendInitiator } from '../nostr/handler.js'; +import { UnsignedEvent } from 'nostr-tools'; export const expirationRuleName = 'expiration' export const frequencyRuleName = 'frequency' type RecurringDebitTimeUnit = 'day' | 'week' | 'month' @@ -111,6 +113,7 @@ type HandleNdebitRes = { status: 'fail', debitRes: NdebitFailure } export class DebitManager { + _nostrSend: NostrSend | null = null applicationManager: ApplicationManager @@ -123,12 +126,25 @@ export class DebitManager { this.applicationManager = applicationManager } + attachNostrSend = (nostrSend: NostrSend) => { + this._nostrSend = nostrSend + } + nostrSend: NostrSend = (initiator: SendInitiator, data: SendData, relays?: string[] | undefined) => { + if (!this._nostrSend) { + throw new Error("No nostrSend attached") + } + this._nostrSend(initiator, data, relays) + } + AuthorizeDebit = async (ctx: Types.UserContext, req: Types.DebitAuthorizationRequest): Promise => { const access = await this.storage.debitStorage.AddDebitAccess(ctx.app_user_id, { authorize: true, npub: req.authorize_npub, rules: debitRulesToDebitAccessRules(req.rules) }) + if (req.request_id) { + this.sendDebitResponse({ res: 'ok' }, { pub: req.authorize_npub, id: req.request_id, appId: ctx.app_id }) + } return { debit_id: access.serial_id.toString(), npub: req.authorize_npub, @@ -163,16 +179,71 @@ export class DebitManager { await this.storage.debitStorage.RemoveDebitAccess(ctx.app_user_id, req.npub) } - payNdebitInvoice = async (appId: string, requestorPub: string, pointerdata: NdebitData): Promise => { + RespondToDebit = async (ctx: Types.UserContext, req: Types.DebitResponse): Promise => { + switch (req.response.type) { + case Types.DebitResponse_response_type.DENIED: + this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: req.npub, id: req.request_id, appId: ctx.app_id }) + return + case Types.DebitResponse_response_type.INVOICE: + const app = await this.storage.applicationStorage.GetApplication(ctx.app_id) + const appUser = await this.storage.applicationStorage.GetApplicationUser(app, ctx.app_user_id) + const { op, payment } = await this.sendDebitPayment(ctx.app_id, ctx.app_user_id, req.npub, req.response.invoice) + const debitRes: NdebitSuccessPayment = { res: 'ok', preimage: payment.preimage } + this.notifyPaymentSuccess(appUser, debitRes, op, { appId: ctx.app_id, pub: req.npub, id: req.request_id }) + return + default: + throw new Error("invalid response type") + } + } + + handleNip68Debit = async (pointerdata: NdebitData, event: NostrEvent) => { + if (!this._nostrSend) { + throw new Error("No nostrSend attached") + } + console.log({ pointerdata, event }) + const res = await this.payNdebitInvoice(event, pointerdata) + console.log({ debitRes: res }) + if (res.status === 'fail' || res.status === 'authOk') { + const e = newNdebitResponse(JSON.stringify(res.debitRes), event) + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + return + } + const { appUser } = res + if (res.status === 'authRequired') { + const message: Types.LiveDebitRequest & { requestId: string, status: 'OK' } = { ...res.liveDebitReq, requestId: "GetLiveDebitRequests", status: 'OK' } + if (appUser.nostr_public_key) {// TODO - fix before support for http streams + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'content', content: JSON.stringify(message), pub: appUser.nostr_public_key }) + } + return + } + const { op, debitRes } = res + this.notifyPaymentSuccess(appUser, debitRes, op, event) + } + + notifyPaymentSuccess = (appUser: ApplicationUser, debitRes: NdebitSuccessPayment, op: Types.UserOperation, event: { pub: string, id: string, appId: string }) => { + const message: Types.LiveUserOperation & { requestId: string, status: 'OK' } = { operation: op, requestId: "GetLiveUserOperations", status: 'OK' } + if (appUser.nostr_public_key) { // TODO - fix before support for http streams + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'content', content: JSON.stringify(message), pub: appUser.nostr_public_key }) + } + this.sendDebitResponse(debitRes, event) + } + + sendDebitResponse = (debitRes: NdebitFailure | NdebitSuccess | NdebitSuccessPayment, event: { pub: string, id: string, appId: string }) => { + const e = newNdebitResponse(JSON.stringify(debitRes), event) + this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) + } + + payNdebitInvoice = async (event: NostrEvent, pointerdata: NdebitData): Promise => { try { - return await this.doNdebit(appId, requestorPub, pointerdata) + return await this.doNdebit(event, pointerdata) } catch (e: any) { this.logger(ERROR, e.message || e) return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } } } } - doNdebit = async (appId: string, requestorPub: string, pointerdata: NdebitData): Promise => { + doNdebit = async (event: NostrEvent, pointerdata: NdebitData): Promise => { + const { appId, pub: requestorPub } = event const { amount_sats, pointer } = pointerdata if (!pointer) { // TODO: debit from app owner balance @@ -190,6 +261,7 @@ export class DebitManager { if (!debitAccess) { return { status: 'authRequired', app, appUser, liveDebitReq: { + request_id: event.id, npub: requestorPub, debit: { type: Types.LiveDebitRequest_debit_type.FREQUENCY, @@ -222,6 +294,7 @@ export class DebitManager { if (!authorization) { return { status: 'authRequired', app, appUser, liveDebitReq: { + request_id: event.id, npub: requestorPub, debit: { type: Types.LiveDebitRequest_debit_type.INVOICE, @@ -234,10 +307,15 @@ export class DebitManager { return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } } } await this.validateAccessRules(authorization, app, appUser) + const { op, payment } = await this.sendDebitPayment(appId, appUserId, requestorPub, bolt11) + return { status: 'invoicePaid', op, app, appUser, debitRes: { res: 'ok', preimage: payment.preimage } } + } + + sendDebitPayment = async (appId: string, appUserId: string, requestorPub: string, bolt11: string) => { const payment = await this.applicationManager.PayAppUserInvoice(appId, { amount: 0, invoice: bolt11, user_identifier: appUserId, debit_npub: requestorPub }) await this.storage.debitStorage.IncrementDebitAccess(appUserId, requestorPub, payment.amount_paid + payment.service_fee + payment.network_fee) const op = this.newPaymentOperation(payment, bolt11) - return { status: 'invoicePaid', op, app, appUser, debitRes: { res: 'ok', preimage: payment.preimage } } + return { payment, op } } validateAccessRules = async (access: DebitAccess, app: Application, appUser: ApplicationUser): Promise => { @@ -286,3 +364,15 @@ export class DebitManager { } } +const newNdebitResponse = (content: string, event: { pub: string, id: string }): UnsignedEvent => { + return { + content, + created_at: Math.floor(Date.now() / 1000), + kind: 21002, + pubkey: "", + tags: [ + ['p', event.pub], + ['e', event.id], + ], + } +} \ No newline at end of file diff --git a/src/services/main/index.ts b/src/services/main/index.ts index e93f9da0..5c2936d6 100644 --- a/src/services/main/index.ts +++ b/src/services/main/index.ts @@ -88,6 +88,7 @@ export default class { attachNostrSend(f: NostrSend) { this.nostrSend = f this.liquidityProvider.attachNostrSend(f) + this.debitManager.attachNostrSend(f) } htlcCb: HtlcCb = (e) => { @@ -319,31 +320,7 @@ export default class { return } - handleNip68Debit = async (pointerdata: NdebitData, event: NostrEvent) => { - console.log({ pointerdata, event }) - const res = await this.debitManager.payNdebitInvoice(event.appId, event.pub, pointerdata) - console.log({ debitRes: res }) - if (res.status === 'fail' || res.status === 'authOk') { - const e = newNdebitResponse(JSON.stringify(res.debitRes), event) - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) - return - } - const { appUser } = res - if (res.status === 'authRequired') { - const message: Types.LiveDebitRequest & { requestId: string, status: 'OK' } = { ...res.liveDebitReq, requestId: "GetLiveDebitRequests", status: 'OK' } - if (appUser.nostr_public_key) {// TODO - fix before support for http streams - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'content', content: JSON.stringify(message), pub: appUser.nostr_public_key }) - } - return - } - const { op, debitRes } = res - const message: Types.LiveUserOperation & { requestId: string, status: 'OK' } = { operation: op, requestId: "GetLiveUserOperations", status: 'OK' } - if (appUser.nostr_public_key) { // TODO - fix before support for http streams - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'content', content: JSON.stringify(message), pub: appUser.nostr_public_key }) - } - const e = newNdebitResponse(JSON.stringify(debitRes), event) - this.nostrSend({ type: 'app', appId: event.appId }, { type: 'event', event: e, encrypt: { toPub: event.pub } }) - } + } const codeToMessage = (code: number) => { @@ -370,15 +347,4 @@ const newNofferResponse = (content: string, event: NostrEvent): UnsignedEvent => } } -const newNdebitResponse = (content: string, event: NostrEvent): UnsignedEvent => { - return { - content, - created_at: Math.floor(Date.now() / 1000), - kind: 21002, - pubkey: "", - tags: [ - ['p', event.pub], - ['e', event.id], - ], - } -} + diff --git a/src/services/serverMethods/index.ts b/src/services/serverMethods/index.ts index ebde0728..b116406d 100644 --- a/src/services/serverMethods/index.ts +++ b/src/services/serverMethods/index.ts @@ -288,7 +288,9 @@ export default (mainHandler: Main): Types.ServerMethods => { }, EditDebit: async ({ ctx, req }) => { return mainHandler.debitManager.EditDebit(ctx, req); + }, + RespondToDebit: async ({ ctx, req }) => { + return mainHandler.debitManager.RespondToDebit(ctx, req); } - } } \ No newline at end of file