response to service
This commit is contained in:
parent
d2f2ac48eb
commit
1049586646
15 changed files with 354 additions and 51 deletions
|
|
@ -200,6 +200,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- input: [DebitOperation](#DebitOperation)
|
- input: [DebitOperation](#DebitOperation)
|
||||||
- This methods has an __empty__ __response__ body
|
- This methods has an __empty__ __response__ body
|
||||||
|
|
||||||
|
- RespondToDebit
|
||||||
|
- auth type: __User__
|
||||||
|
- input: [DebitResponse](#DebitResponse)
|
||||||
|
- This methods has an __empty__ __response__ body
|
||||||
|
|
||||||
- UpdateCallbackUrl
|
- UpdateCallbackUrl
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- input: [CallbackUrl](#CallbackUrl)
|
- 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)
|
- input: [RequestNPubLinkingTokenRequest](#RequestNPubLinkingTokenRequest)
|
||||||
- output: [RequestNPubLinkingTokenResponse](#RequestNPubLinkingTokenResponse)
|
- 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
|
- SendAppUserToAppPayment
|
||||||
- auth type: __App__
|
- auth type: __App__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -797,6 +809,7 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
|
|
||||||
### DebitAuthorizationRequest
|
### DebitAuthorizationRequest
|
||||||
- __authorize_npub__: _string_
|
- __authorize_npub__: _string_
|
||||||
|
- __request_id__: _string_ *this field is optional
|
||||||
- __rules__: ARRAY of: _[DebitRule](#DebitRule)_
|
- __rules__: ARRAY of: _[DebitRule](#DebitRule)_
|
||||||
|
|
||||||
### DebitAuthorizations
|
### DebitAuthorizations
|
||||||
|
|
@ -808,6 +821,11 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
### DebitOperation
|
### DebitOperation
|
||||||
- __npub__: _string_
|
- __npub__: _string_
|
||||||
|
|
||||||
|
### DebitResponse
|
||||||
|
- __npub__: _string_
|
||||||
|
- __request_id__: _string_
|
||||||
|
- __response__: _[DebitResponse_response](#DebitResponse_response)_
|
||||||
|
|
||||||
### DebitRule
|
### DebitRule
|
||||||
- __rule__: _[DebitRule_rule](#DebitRule_rule)_
|
- __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
|
### LiveDebitRequest
|
||||||
- __debit__: _[LiveDebitRequest_debit](#LiveDebitRequest_debit)_
|
- __debit__: _[LiveDebitRequest_debit](#LiveDebitRequest_debit)_
|
||||||
- __npub__: _string_
|
- __npub__: _string_
|
||||||
|
- __request_id__: _string_
|
||||||
|
|
||||||
### LiveUserOperation
|
### LiveUserOperation
|
||||||
- __operation__: _[UserOperation](#UserOperation)_
|
- __operation__: _[UserOperation](#UserOperation)_
|
||||||
|
|
|
||||||
|
|
@ -107,6 +107,7 @@ type Client struct {
|
||||||
RequestNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error)
|
RequestNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error)
|
||||||
ResetDebit func(req DebitOperation) error
|
ResetDebit func(req DebitOperation) error
|
||||||
ResetNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error)
|
ResetNPubLinkingToken func(req RequestNPubLinkingTokenRequest) (*RequestNPubLinkingTokenResponse, error)
|
||||||
|
RespondToDebit func(req DebitResponse) error
|
||||||
SendAppUserToAppPayment func(req SendAppUserToAppPaymentRequest) error
|
SendAppUserToAppPayment func(req SendAppUserToAppPaymentRequest) error
|
||||||
SendAppUserToAppUserPayment func(req SendAppUserToAppUserPaymentRequest) error
|
SendAppUserToAppUserPayment func(req SendAppUserToAppUserPaymentRequest) error
|
||||||
SetMockAppBalance func(req SetMockAppBalanceRequest) error
|
SetMockAppBalance func(req SetMockAppBalanceRequest) error
|
||||||
|
|
@ -1433,6 +1434,30 @@ func NewClient(params ClientParams) *Client {
|
||||||
}
|
}
|
||||||
return &res, nil
|
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 {
|
SendAppUserToAppPayment: func(req SendAppUserToAppPaymentRequest) error {
|
||||||
auth, err := params.RetrieveAppAuth()
|
auth, err := params.RetrieveAppAuth()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -175,6 +175,7 @@ type DebitAuthorization struct {
|
||||||
}
|
}
|
||||||
type DebitAuthorizationRequest struct {
|
type DebitAuthorizationRequest struct {
|
||||||
Authorize_npub string `json:"authorize_npub"`
|
Authorize_npub string `json:"authorize_npub"`
|
||||||
|
Request_id string `json:"request_id"`
|
||||||
Rules []DebitRule `json:"rules"`
|
Rules []DebitRule `json:"rules"`
|
||||||
}
|
}
|
||||||
type DebitAuthorizations struct {
|
type DebitAuthorizations struct {
|
||||||
|
|
@ -186,6 +187,11 @@ type DebitExpirationRule struct {
|
||||||
type DebitOperation struct {
|
type DebitOperation struct {
|
||||||
Npub string `json:"npub"`
|
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 {
|
type DebitRule struct {
|
||||||
Rule *DebitRule_rule `json:"rule"`
|
Rule *DebitRule_rule `json:"rule"`
|
||||||
}
|
}
|
||||||
|
|
@ -261,8 +267,9 @@ type LinkNPubThroughTokenRequest struct {
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
}
|
}
|
||||||
type LiveDebitRequest struct {
|
type LiveDebitRequest struct {
|
||||||
Debit *LiveDebitRequest_debit `json:"debit"`
|
Debit *LiveDebitRequest_debit `json:"debit"`
|
||||||
Npub string `json:"npub"`
|
Npub string `json:"npub"`
|
||||||
|
Request_id string `json:"request_id"`
|
||||||
}
|
}
|
||||||
type LiveUserOperation struct {
|
type LiveUserOperation struct {
|
||||||
Operation *UserOperation `json:"operation"`
|
Operation *UserOperation `json:"operation"`
|
||||||
|
|
@ -497,6 +504,18 @@ type UsersInfo struct {
|
||||||
No_balance int64 `json:"no_balance"`
|
No_balance int64 `json:"no_balance"`
|
||||||
Total int64 `json:"total"`
|
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
|
type DebitRule_rule_type string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
|
||||||
|
|
@ -481,6 +481,18 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
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':
|
case 'UpdateCallbackUrl':
|
||||||
if (!methods.UpdateCallbackUrl) {
|
if (!methods.UpdateCallbackUrl) {
|
||||||
throw new Error('method UpdateCallbackUrl not found' )
|
throw new Error('method UpdateCallbackUrl not found' )
|
||||||
|
|
@ -1323,6 +1335,28 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
})
|
})
|
||||||
|
if (!opts.allowNotImplementedMethods && !methods.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')
|
if (!opts.allowNotImplementedMethods && !methods.SendAppUserToAppPayment) throw new Error('method: SendAppUserToAppPayment is not implemented')
|
||||||
app.post('/api/app/internal/pay', async (req, res) => {
|
app.post('/api/app/internal/pay', async (req, res) => {
|
||||||
const info: Types.RequestInfo = { rpcName: 'SendAppUserToAppPayment', batch: false, nostr: false, batchSize: 0}
|
const info: Types.RequestInfo = { rpcName: 'SendAppUserToAppPayment', batch: false, nostr: false, batchSize: 0}
|
||||||
|
|
|
||||||
|
|
@ -691,6 +691,17 @@ export default (params: ClientParams) => ({
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
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' })> => {
|
SendAppUserToAppPayment: async (request: Types.SendAppUserToAppPaymentRequest): Promise<ResultError | ({ status: 'OK' })> => {
|
||||||
const auth = await params.retrieveAppAuth()
|
const auth = await params.retrieveAppAuth()
|
||||||
if (auth === null) throw new Error('retrieveAppAuth() returned null')
|
if (auth === null) throw new Error('retrieveAppAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -540,6 +540,18 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
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)> => {
|
UpdateCallbackUrl: async (request: Types.CallbackUrl): Promise<ResultError | ({ status: 'OK' }& Types.CallbackUrl)> => {
|
||||||
const auth = await params.retrieveNostrUserAuth()
|
const auth = await params.retrieveNostrUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveNostrUserAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -375,6 +375,18 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
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':
|
case 'UpdateCallbackUrl':
|
||||||
if (!methods.UpdateCallbackUrl) {
|
if (!methods.UpdateCallbackUrl) {
|
||||||
throw new Error('method not defined: UpdateCallbackUrl')
|
throw new Error('method not defined: UpdateCallbackUrl')
|
||||||
|
|
@ -848,6 +860,22 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
||||||
break
|
break
|
||||||
|
case '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':
|
case 'UpdateCallbackUrl':
|
||||||
try {
|
try {
|
||||||
if (!methods.UpdateCallbackUrl) throw new Error('method: UpdateCallbackUrl is not implemented')
|
if (!methods.UpdateCallbackUrl) throw new Error('method: UpdateCallbackUrl is not implemented')
|
||||||
|
|
|
||||||
|
|
@ -34,8 +34,8 @@ export type UserContext = {
|
||||||
app_user_id: string
|
app_user_id: string
|
||||||
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 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 | UpdateCallbackUrl_Output | UserHealth_Output
|
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 AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
|
||||||
|
|
||||||
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
|
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_Input = {rpcName:'ResetNPubLinkingToken', req: RequestNPubLinkingTokenRequest}
|
||||||
export type ResetNPubLinkingToken_Output = ResultError | ({ status: 'OK' } & RequestNPubLinkingTokenResponse)
|
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_Input = {rpcName:'SendAppUserToAppPayment', req: SendAppUserToAppPaymentRequest}
|
||||||
export type SendAppUserToAppPayment_Output = ResultError | { status: 'OK' }
|
export type SendAppUserToAppPayment_Output = ResultError | { status: 'OK' }
|
||||||
|
|
||||||
|
|
@ -296,6 +299,7 @@ export type ServerMethods = {
|
||||||
RequestNPubLinkingToken?: (req: RequestNPubLinkingToken_Input & {ctx: AppContext }) => Promise<RequestNPubLinkingTokenResponse>
|
RequestNPubLinkingToken?: (req: RequestNPubLinkingToken_Input & {ctx: AppContext }) => Promise<RequestNPubLinkingTokenResponse>
|
||||||
ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise<void>
|
ResetDebit?: (req: ResetDebit_Input & {ctx: UserContext }) => Promise<void>
|
||||||
ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise<RequestNPubLinkingTokenResponse>
|
ResetNPubLinkingToken?: (req: ResetNPubLinkingToken_Input & {ctx: AppContext }) => Promise<RequestNPubLinkingTokenResponse>
|
||||||
|
RespondToDebit?: (req: RespondToDebit_Input & {ctx: UserContext }) => Promise<void>
|
||||||
SendAppUserToAppPayment?: (req: SendAppUserToAppPayment_Input & {ctx: AppContext }) => Promise<void>
|
SendAppUserToAppPayment?: (req: SendAppUserToAppPayment_Input & {ctx: AppContext }) => Promise<void>
|
||||||
SendAppUserToAppUserPayment?: (req: SendAppUserToAppUserPayment_Input & {ctx: AppContext }) => Promise<void>
|
SendAppUserToAppUserPayment?: (req: SendAppUserToAppUserPayment_Input & {ctx: AppContext }) => Promise<void>
|
||||||
SetMockAppBalance?: (req: SetMockAppBalance_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 = {
|
export type DebitAuthorizationRequest = {
|
||||||
authorize_npub: string
|
authorize_npub: string
|
||||||
|
request_id?: string
|
||||||
rules: DebitRule[]
|
rules: DebitRule[]
|
||||||
}
|
}
|
||||||
export const DebitAuthorizationRequestOptionalFields: [] = []
|
export type DebitAuthorizationRequestOptionalField = 'request_id'
|
||||||
|
export const DebitAuthorizationRequestOptionalFields: DebitAuthorizationRequestOptionalField[] = ['request_id']
|
||||||
export type DebitAuthorizationRequestOptions = OptionsBaseMessage & {
|
export type DebitAuthorizationRequestOptions = OptionsBaseMessage & {
|
||||||
checkOptionalsAreSet?: []
|
checkOptionalsAreSet?: DebitAuthorizationRequestOptionalField[]
|
||||||
authorize_npub_CustomCheck?: (v: string) => boolean
|
authorize_npub_CustomCheck?: (v: string) => boolean
|
||||||
|
request_id_CustomCheck?: (v?: string) => boolean
|
||||||
rules_ItemOptions?: DebitRuleOptions
|
rules_ItemOptions?: DebitRuleOptions
|
||||||
rules_CustomCheck?: (v: DebitRule[]) => boolean
|
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 (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 (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`)
|
if (!Array.isArray(o.rules)) return new Error(`${path}.rules: is not an array`)
|
||||||
for (let index = 0; index < o.rules.length; index++) {
|
for (let index = 0; index < o.rules.length; index++) {
|
||||||
const rulesErr = DebitRuleValidate(o.rules[index], opts.rules_ItemOptions, `${path}.rules[${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
|
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 = {
|
export type DebitRule = {
|
||||||
rule: DebitRule_rule
|
rule: DebitRule_rule
|
||||||
}
|
}
|
||||||
|
|
@ -1452,12 +1491,14 @@ export const LinkNPubThroughTokenRequestValidate = (o?: LinkNPubThroughTokenRequ
|
||||||
export type LiveDebitRequest = {
|
export type LiveDebitRequest = {
|
||||||
debit: LiveDebitRequest_debit
|
debit: LiveDebitRequest_debit
|
||||||
npub: string
|
npub: string
|
||||||
|
request_id: string
|
||||||
}
|
}
|
||||||
export const LiveDebitRequestOptionalFields: [] = []
|
export const LiveDebitRequestOptionalFields: [] = []
|
||||||
export type LiveDebitRequestOptions = OptionsBaseMessage & {
|
export type LiveDebitRequestOptions = OptionsBaseMessage & {
|
||||||
checkOptionalsAreSet?: []
|
checkOptionalsAreSet?: []
|
||||||
debit_Options?: LiveDebitRequest_debitOptions
|
debit_Options?: LiveDebitRequest_debitOptions
|
||||||
npub_CustomCheck?: (v: string) => boolean
|
npub_CustomCheck?: (v: string) => boolean
|
||||||
|
request_id_CustomCheck?: (v: string) => boolean
|
||||||
}
|
}
|
||||||
export const LiveDebitRequestValidate = (o?: LiveDebitRequest, opts: LiveDebitRequestOptions = {}, path: string = 'LiveDebitRequest::root.'): Error | null => {
|
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')
|
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 (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 (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
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2826,6 +2870,42 @@ export const UsersInfoValidate = (o?: UsersInfo, opts: UsersInfoOptions = {}, pa
|
||||||
return null
|
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 {
|
export enum DebitRule_rule_type {
|
||||||
EXPIRATION_RULE = 'expiration_rule',
|
EXPIRATION_RULE = 'expiration_rule',
|
||||||
FREQUENCY_RULE = 'frequency_rule',
|
FREQUENCY_RULE = 'frequency_rule',
|
||||||
|
|
|
||||||
|
|
@ -471,6 +471,12 @@ service LightningPub {
|
||||||
option (http_route) = "/api/user/debit/reset";
|
option (http_route) = "/api/user/debit/reset";
|
||||||
option (nostr) = true;
|
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){
|
rpc GetLiveDebitRequests(structs.Empty) returns (stream structs.LiveDebitRequest){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
|
|
|
||||||
|
|
@ -493,6 +493,7 @@ message DebitOperation {
|
||||||
message DebitAuthorizationRequest {
|
message DebitAuthorizationRequest {
|
||||||
string authorize_npub = 1;
|
string authorize_npub = 1;
|
||||||
repeated DebitRule rules = 2;
|
repeated DebitRule rules = 2;
|
||||||
|
optional string request_id = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
message DebitAuthorization {
|
message DebitAuthorization {
|
||||||
|
|
@ -530,9 +531,19 @@ message DebitRule {
|
||||||
}
|
}
|
||||||
|
|
||||||
message LiveDebitRequest {
|
message LiveDebitRequest {
|
||||||
string npub = 1;
|
string request_id = 1;
|
||||||
|
string npub = 2;
|
||||||
oneof debit {
|
oneof debit {
|
||||||
string invoice = 3;
|
string invoice = 3;
|
||||||
FrequencyRule frequency = 4;
|
FrequencyRule frequency = 4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message DebitResponse {
|
||||||
|
string request_id = 1;
|
||||||
|
string npub = 2;
|
||||||
|
oneof response {
|
||||||
|
Empty denied = 3;
|
||||||
|
string invoice = 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -52,7 +52,7 @@ export default (serverMethods: Types.ServerMethods, mainHandler: Main, nostrSett
|
||||||
return
|
return
|
||||||
} else if (event.kind === 21002) {
|
} else if (event.kind === 21002) {
|
||||||
const debitReq = j as NdebitData
|
const debitReq = j as NdebitData
|
||||||
mainHandler.handleNip68Debit(debitReq, event)
|
mainHandler.debitManager.handleNip68Debit(debitReq, event)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!j.rpcName) {
|
if (!j.rpcName) {
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,8 @@ import { DebitAccess, DebitAccessRules } from '../storage/entity/DebitAccess.js'
|
||||||
import paymentManager from './paymentManager.js';
|
import paymentManager from './paymentManager.js';
|
||||||
import { Application } from '../storage/entity/Application.js';
|
import { Application } from '../storage/entity/Application.js';
|
||||||
import { ApplicationUser } from '../storage/entity/ApplicationUser.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 expirationRuleName = 'expiration'
|
||||||
export const frequencyRuleName = 'frequency'
|
export const frequencyRuleName = 'frequency'
|
||||||
type RecurringDebitTimeUnit = 'day' | 'week' | 'month'
|
type RecurringDebitTimeUnit = 'day' | 'week' | 'month'
|
||||||
|
|
@ -111,6 +113,7 @@ type HandleNdebitRes = { status: 'fail', debitRes: NdebitFailure }
|
||||||
export class DebitManager {
|
export class DebitManager {
|
||||||
|
|
||||||
|
|
||||||
|
_nostrSend: NostrSend | null = null
|
||||||
|
|
||||||
applicationManager: ApplicationManager
|
applicationManager: ApplicationManager
|
||||||
|
|
||||||
|
|
@ -123,12 +126,25 @@ export class DebitManager {
|
||||||
this.applicationManager = applicationManager
|
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<Types.DebitAuthorization> => {
|
AuthorizeDebit = async (ctx: Types.UserContext, req: Types.DebitAuthorizationRequest): Promise<Types.DebitAuthorization> => {
|
||||||
const access = await this.storage.debitStorage.AddDebitAccess(ctx.app_user_id, {
|
const access = await this.storage.debitStorage.AddDebitAccess(ctx.app_user_id, {
|
||||||
authorize: true,
|
authorize: true,
|
||||||
npub: req.authorize_npub,
|
npub: req.authorize_npub,
|
||||||
rules: debitRulesToDebitAccessRules(req.rules)
|
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 {
|
return {
|
||||||
debit_id: access.serial_id.toString(),
|
debit_id: access.serial_id.toString(),
|
||||||
npub: req.authorize_npub,
|
npub: req.authorize_npub,
|
||||||
|
|
@ -163,16 +179,71 @@ export class DebitManager {
|
||||||
await this.storage.debitStorage.RemoveDebitAccess(ctx.app_user_id, req.npub)
|
await this.storage.debitStorage.RemoveDebitAccess(ctx.app_user_id, req.npub)
|
||||||
}
|
}
|
||||||
|
|
||||||
payNdebitInvoice = async (appId: string, requestorPub: string, pointerdata: NdebitData): Promise<HandleNdebitRes> => {
|
RespondToDebit = async (ctx: Types.UserContext, req: Types.DebitResponse): Promise<void> => {
|
||||||
|
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<HandleNdebitRes> => {
|
||||||
try {
|
try {
|
||||||
return await this.doNdebit(appId, requestorPub, pointerdata)
|
return await this.doNdebit(event, pointerdata)
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
this.logger(ERROR, e.message || e)
|
this.logger(ERROR, e.message || e)
|
||||||
return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } }
|
return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
doNdebit = async (appId: string, requestorPub: string, pointerdata: NdebitData): Promise<HandleNdebitRes> => {
|
doNdebit = async (event: NostrEvent, pointerdata: NdebitData): Promise<HandleNdebitRes> => {
|
||||||
|
const { appId, pub: requestorPub } = event
|
||||||
const { amount_sats, pointer } = pointerdata
|
const { amount_sats, pointer } = pointerdata
|
||||||
if (!pointer) {
|
if (!pointer) {
|
||||||
// TODO: debit from app owner balance
|
// TODO: debit from app owner balance
|
||||||
|
|
@ -190,6 +261,7 @@ export class DebitManager {
|
||||||
if (!debitAccess) {
|
if (!debitAccess) {
|
||||||
return {
|
return {
|
||||||
status: 'authRequired', app, appUser, liveDebitReq: {
|
status: 'authRequired', app, appUser, liveDebitReq: {
|
||||||
|
request_id: event.id,
|
||||||
npub: requestorPub,
|
npub: requestorPub,
|
||||||
debit: {
|
debit: {
|
||||||
type: Types.LiveDebitRequest_debit_type.FREQUENCY,
|
type: Types.LiveDebitRequest_debit_type.FREQUENCY,
|
||||||
|
|
@ -222,6 +294,7 @@ export class DebitManager {
|
||||||
if (!authorization) {
|
if (!authorization) {
|
||||||
return {
|
return {
|
||||||
status: 'authRequired', app, appUser, liveDebitReq: {
|
status: 'authRequired', app, appUser, liveDebitReq: {
|
||||||
|
request_id: event.id,
|
||||||
npub: requestorPub,
|
npub: requestorPub,
|
||||||
debit: {
|
debit: {
|
||||||
type: Types.LiveDebitRequest_debit_type.INVOICE,
|
type: Types.LiveDebitRequest_debit_type.INVOICE,
|
||||||
|
|
@ -234,10 +307,15 @@ export class DebitManager {
|
||||||
return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } }
|
return { status: 'fail', debitRes: { res: 'GFY', error: nip68errs[1], code: 1 } }
|
||||||
}
|
}
|
||||||
await this.validateAccessRules(authorization, app, appUser)
|
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 })
|
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)
|
await this.storage.debitStorage.IncrementDebitAccess(appUserId, requestorPub, payment.amount_paid + payment.service_fee + payment.network_fee)
|
||||||
const op = this.newPaymentOperation(payment, bolt11)
|
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<boolean> => {
|
validateAccessRules = async (access: DebitAccess, app: Application, appUser: ApplicationUser): Promise<boolean> => {
|
||||||
|
|
@ -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],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -88,6 +88,7 @@ export default class {
|
||||||
attachNostrSend(f: NostrSend) {
|
attachNostrSend(f: NostrSend) {
|
||||||
this.nostrSend = f
|
this.nostrSend = f
|
||||||
this.liquidityProvider.attachNostrSend(f)
|
this.liquidityProvider.attachNostrSend(f)
|
||||||
|
this.debitManager.attachNostrSend(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
htlcCb: HtlcCb = (e) => {
|
htlcCb: HtlcCb = (e) => {
|
||||||
|
|
@ -319,31 +320,7 @@ export default class {
|
||||||
return
|
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) => {
|
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],
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -288,7 +288,9 @@ export default (mainHandler: Main): Types.ServerMethods => {
|
||||||
},
|
},
|
||||||
EditDebit: async ({ ctx, req }) => {
|
EditDebit: async ({ ctx, req }) => {
|
||||||
return mainHandler.debitManager.EditDebit(ctx, req);
|
return mainHandler.debitManager.EditDebit(ctx, req);
|
||||||
|
},
|
||||||
|
RespondToDebit: async ({ ctx, req }) => {
|
||||||
|
return mainHandler.debitManager.RespondToDebit(ctx, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue