response to service

This commit is contained in:
boufni95 2024-10-03 16:56:54 +00:00
parent d2f2ac48eb
commit 1049586646
15 changed files with 354 additions and 51 deletions

View file

@ -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)_

View file

@ -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 {

View file

@ -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 (

View file

@ -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}

View file

@ -691,6 +691,17 @@ export default (params: ClientParams) => ({
}
return { status: 'ERROR', reason: 'invalid response' }
},
RespondToDebit: async (request: Types.DebitResponse): Promise<ResultError | ({ status: 'OK' })> => {
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<ResultError | ({ status: 'OK' })> => {
const auth = await params.retrieveAppAuth()
if (auth === null) throw new Error('retrieveAppAuth() returned null')

View file

@ -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<ResultError | ({ status: 'OK' })> => {
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<ResultError | ({ status: 'OK' }& Types.CallbackUrl)> => {
const auth = await params.retrieveNostrUserAuth()
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')

View file

@ -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')

View file

@ -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<RequestNPubLinkingTokenResponse>
ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise<void>
ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise<RequestNPubLinkingTokenResponse>
RespondToDebit?: (req: RespondToDebit_Input & {ctx: UserContext }) => Promise<void>
SendAppUserToAppPayment?: (req: SendAppUserToAppPayment_Input & {ctx: AppContext }) => Promise<void>
SendAppUserToAppUserPayment?: (req: SendAppUserToAppUserPayment_Input & {ctx: AppContext }) => Promise<void>
SetMockAppBalance?: (req: SetMockAppBalance_Input & {ctx: AppContext }) => Promise<void>
@ -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',