fix initial invoice ack
This commit is contained in:
parent
c31360b0cd
commit
c85ea7ff57
12 changed files with 239 additions and 263 deletions
|
|
@ -38,11 +38,6 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- input: [AuthAppRequest](#AuthAppRequest)
|
- input: [AuthAppRequest](#AuthAppRequest)
|
||||||
- output: [AuthApp](#AuthApp)
|
- output: [AuthApp](#AuthApp)
|
||||||
|
|
||||||
- AuthorizeDebit
|
|
||||||
- auth type: __User__
|
|
||||||
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
|
||||||
- output: [DebitAuthorization](#DebitAuthorization)
|
|
||||||
|
|
||||||
- AuthorizeManage
|
- AuthorizeManage
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- input: [ManageAuthorizationRequest](#ManageAuthorizationRequest)
|
- input: [ManageAuthorizationRequest](#ManageAuthorizationRequest)
|
||||||
|
|
@ -436,13 +431,6 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
- input: [AuthAppRequest](#AuthAppRequest)
|
- input: [AuthAppRequest](#AuthAppRequest)
|
||||||
- output: [AuthApp](#AuthApp)
|
- output: [AuthApp](#AuthApp)
|
||||||
|
|
||||||
- AuthorizeDebit
|
|
||||||
- auth type: __User__
|
|
||||||
- http method: __post__
|
|
||||||
- http route: __/api/user/debit/authorize__
|
|
||||||
- input: [DebitAuthorizationRequest](#DebitAuthorizationRequest)
|
|
||||||
- output: [DebitAuthorization](#DebitAuthorization)
|
|
||||||
|
|
||||||
- AuthorizeManage
|
- AuthorizeManage
|
||||||
- auth type: __User__
|
- auth type: __User__
|
||||||
- http method: __post__
|
- http method: __post__
|
||||||
|
|
@ -1177,6 +1165,10 @@ The nostr server will send back a message response, and inside the body there wi
|
||||||
### DebitRule
|
### DebitRule
|
||||||
- __rule__: _[DebitRule_rule](#DebitRule_rule)_
|
- __rule__: _[DebitRule_rule](#DebitRule_rule)_
|
||||||
|
|
||||||
|
### DebitToAuthorize
|
||||||
|
- __invoice__: _string_ *this field is optional
|
||||||
|
- __rules__: ARRAY of: _[DebitRule](#DebitRule)_
|
||||||
|
|
||||||
### DecodeInvoiceRequest
|
### DecodeInvoiceRequest
|
||||||
- __invoice__: _string_
|
- __invoice__: _string_
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,6 @@ type Client struct {
|
||||||
AddProduct func(req AddProductRequest) (*Product, error)
|
AddProduct func(req AddProductRequest) (*Product, error)
|
||||||
AddUserOffer func(req OfferConfig) (*OfferId, error)
|
AddUserOffer func(req OfferConfig) (*OfferId, error)
|
||||||
AuthApp func(req AuthAppRequest) (*AuthApp, error)
|
AuthApp func(req AuthAppRequest) (*AuthApp, error)
|
||||||
AuthorizeDebit func(req DebitAuthorizationRequest) (*DebitAuthorization, error)
|
|
||||||
AuthorizeManage func(req ManageAuthorizationRequest) (*ManageAuthorization, error)
|
AuthorizeManage func(req ManageAuthorizationRequest) (*ManageAuthorization, error)
|
||||||
BanDebit func(req DebitOperation) error
|
BanDebit func(req DebitOperation) error
|
||||||
BanUser func(req BanUserRequest) (*BanUserResponse, error)
|
BanUser func(req BanUserRequest) (*BanUserResponse, error)
|
||||||
|
|
@ -373,35 +372,6 @@ func NewClient(params ClientParams) *Client {
|
||||||
}
|
}
|
||||||
return &res, nil
|
return &res, nil
|
||||||
},
|
},
|
||||||
AuthorizeDebit: func(req DebitAuthorizationRequest) (*DebitAuthorization, error) {
|
|
||||||
auth, err := params.RetrieveUserAuth()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
finalRoute := "/api/user/debit/authorize"
|
|
||||||
body, err := json.Marshal(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
resBody, err := doPostRequest(params.BaseURL+finalRoute, body, auth)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
result := ResultError{}
|
|
||||||
err = json.Unmarshal(resBody, &result)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if result.Status == "ERROR" {
|
|
||||||
return nil, fmt.Errorf(result.Reason)
|
|
||||||
}
|
|
||||||
res := DebitAuthorization{}
|
|
||||||
err = json.Unmarshal(resBody, &res)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &res, nil
|
|
||||||
},
|
|
||||||
AuthorizeManage: func(req ManageAuthorizationRequest) (*ManageAuthorization, error) {
|
AuthorizeManage: func(req ManageAuthorizationRequest) (*ManageAuthorization, error) {
|
||||||
auth, err := params.RetrieveUserAuth()
|
auth, err := params.RetrieveUserAuth()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -250,6 +250,10 @@ type DebitResponse struct {
|
||||||
type DebitRule struct {
|
type DebitRule struct {
|
||||||
Rule *DebitRule_rule `json:"rule"`
|
Rule *DebitRule_rule `json:"rule"`
|
||||||
}
|
}
|
||||||
|
type DebitToAuthorize struct {
|
||||||
|
Invoice string `json:"invoice"`
|
||||||
|
Rules []DebitRule `json:"rules"`
|
||||||
|
}
|
||||||
type DecodeInvoiceRequest struct {
|
type DecodeInvoiceRequest struct {
|
||||||
Invoice string `json:"invoice"`
|
Invoice string `json:"invoice"`
|
||||||
}
|
}
|
||||||
|
|
@ -722,12 +726,14 @@ type ZippedMetrics struct {
|
||||||
type DebitResponse_response_type string
|
type DebitResponse_response_type string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
AUTHORIZE DebitResponse_response_type = "authorize"
|
||||||
DENIED DebitResponse_response_type = "denied"
|
DENIED DebitResponse_response_type = "denied"
|
||||||
INVOICE DebitResponse_response_type = "invoice"
|
INVOICE DebitResponse_response_type = "invoice"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DebitResponse_response struct {
|
type DebitResponse_response struct {
|
||||||
Type DebitResponse_response_type `json:"type"`
|
Type DebitResponse_response_type `json:"type"`
|
||||||
|
Authorize *DebitToAuthorize `json:"authorize"`
|
||||||
Denied *Empty `json:"denied"`
|
Denied *Empty `json:"denied"`
|
||||||
Invoice *string `json:"invoice"`
|
Invoice *string `json:"invoice"`
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -210,28 +210,6 @@ 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.AuthorizeDebit) throw new Error('method: AuthorizeDebit is not implemented')
|
|
||||||
app.post('/api/user/debit/authorize', async (req, res) => {
|
|
||||||
const info: Types.RequestInfo = { rpcName: 'AuthorizeDebit', 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.AuthorizeDebit) throw new Error('method: AuthorizeDebit 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.DebitAuthorizationRequestValidate(request)
|
|
||||||
stats.validate = process.hrtime.bigint()
|
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authContext }, opts.metricsCallback)
|
|
||||||
const query = req.query
|
|
||||||
const params = req.params
|
|
||||||
const response = await methods.AuthorizeDebit({rpcName:'AuthorizeDebit', ctx:authContext , req: request})
|
|
||||||
stats.handle = process.hrtime.bigint()
|
|
||||||
res.json({status: 'OK', ...response})
|
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
|
||||||
} catch (ex) { const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
|
||||||
})
|
|
||||||
if (!opts.allowNotImplementedMethods && !methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
if (!opts.allowNotImplementedMethods && !methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
||||||
app.post('/api/user/manage/authorize', async (req, res) => {
|
app.post('/api/user/manage/authorize', async (req, res) => {
|
||||||
const info: Types.RequestInfo = { rpcName: 'AuthorizeManage', batch: false, nostr: false, batchSize: 0}
|
const info: Types.RequestInfo = { rpcName: 'AuthorizeManage', batch: false, nostr: false, batchSize: 0}
|
||||||
|
|
@ -343,18 +321,6 @@ export default (methods: Types.ServerMethods, opts: ServerOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
case 'AuthorizeDebit':
|
|
||||||
if (!methods.AuthorizeDebit) {
|
|
||||||
throw new Error('method AuthorizeDebit not found' )
|
|
||||||
} else {
|
|
||||||
const error = Types.DebitAuthorizationRequestValidate(operation.req)
|
|
||||||
opStats.validate = process.hrtime.bigint()
|
|
||||||
if (error !== null) throw error
|
|
||||||
const res = await methods.AuthorizeDebit({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
|
||||||
opStats.handle = process.hrtime.bigint()
|
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
|
||||||
}
|
|
||||||
break
|
|
||||||
case 'AuthorizeManage':
|
case 'AuthorizeManage':
|
||||||
if (!methods.AuthorizeManage) {
|
if (!methods.AuthorizeManage) {
|
||||||
throw new Error('method AuthorizeManage not found' )
|
throw new Error('method AuthorizeManage not found' )
|
||||||
|
|
|
||||||
|
|
@ -126,20 +126,6 @@ export default (params: ClientParams) => ({
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
AuthorizeDebit: async (request: Types.DebitAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorization)> => {
|
|
||||||
const auth = await params.retrieveUserAuth()
|
|
||||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
|
||||||
let finalRoute = '/api/user/debit/authorize'
|
|
||||||
const { data } = await axios.post(params.baseUrl + finalRoute, request, { headers: { 'authorization': auth } })
|
|
||||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
|
||||||
if (data.status === 'OK') {
|
|
||||||
const result = data
|
|
||||||
if(!params.checkResult) return { status: 'OK', ...result }
|
|
||||||
const error = Types.DebitAuthorizationValidate(result)
|
|
||||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
|
||||||
}
|
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
|
||||||
},
|
|
||||||
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
||||||
const auth = await params.retrieveUserAuth()
|
const auth = await params.retrieveUserAuth()
|
||||||
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
if (auth === null) throw new Error('retrieveUserAuth() returned null')
|
||||||
|
|
|
||||||
|
|
@ -84,21 +84,6 @@ export default (params: NostrClientParams, send: (to:string, message: NostrRequ
|
||||||
}
|
}
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
return { status: 'ERROR', reason: 'invalid response' }
|
||||||
},
|
},
|
||||||
AuthorizeDebit: async (request: Types.DebitAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.DebitAuthorization)> => {
|
|
||||||
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:'AuthorizeDebit',authIdentifier:auth, ...nostrRequest })
|
|
||||||
if (data.status === 'ERROR' && typeof data.reason === 'string') return data
|
|
||||||
if (data.status === 'OK') {
|
|
||||||
const result = data
|
|
||||||
if(!params.checkResult) return { status: 'OK', ...result }
|
|
||||||
const error = Types.DebitAuthorizationValidate(result)
|
|
||||||
if (error === null) { return { status: 'OK', ...result } } else return { status: 'ERROR', reason: error.message }
|
|
||||||
}
|
|
||||||
return { status: 'ERROR', reason: 'invalid response' }
|
|
||||||
},
|
|
||||||
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
AuthorizeManage: async (request: Types.ManageAuthorizationRequest): Promise<ResultError | ({ status: 'OK' }& Types.ManageAuthorization)> => {
|
||||||
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')
|
||||||
|
|
|
||||||
|
|
@ -112,22 +112,6 @@ 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 'AuthorizeDebit':
|
|
||||||
try {
|
|
||||||
if (!methods.AuthorizeDebit) throw new Error('method: AuthorizeDebit 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.DebitAuthorizationRequestValidate(request)
|
|
||||||
stats.validate = process.hrtime.bigint()
|
|
||||||
if (error !== null) return logErrorAndReturnResponse(error, 'invalid request body', res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback)
|
|
||||||
const response = await methods.AuthorizeDebit({rpcName:'AuthorizeDebit', ctx:authContext , req: request})
|
|
||||||
stats.handle = process.hrtime.bigint()
|
|
||||||
res({status: 'OK', ...response})
|
|
||||||
opts.metricsCallback([{ ...info, ...stats, ...authContext }])
|
|
||||||
}catch(ex){ const e = ex as any; logErrorAndReturnResponse(e, e.message || e, res, logger, { ...info, ...stats, ...authCtx }, opts.metricsCallback); if (opts.throwErrors) throw e }
|
|
||||||
break
|
|
||||||
case 'AuthorizeManage':
|
case 'AuthorizeManage':
|
||||||
try {
|
try {
|
||||||
if (!methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
if (!methods.AuthorizeManage) throw new Error('method: AuthorizeManage is not implemented')
|
||||||
|
|
@ -219,18 +203,6 @@ export default (methods: Types.ServerMethods, opts: NostrOptions) => {
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
case 'AuthorizeDebit':
|
|
||||||
if (!methods.AuthorizeDebit) {
|
|
||||||
throw new Error('method not defined: AuthorizeDebit')
|
|
||||||
} else {
|
|
||||||
const error = Types.DebitAuthorizationRequestValidate(operation.req)
|
|
||||||
opStats.validate = process.hrtime.bigint()
|
|
||||||
if (error !== null) throw error
|
|
||||||
const res = await methods.AuthorizeDebit({...operation, ctx}); responses.push({ status: 'OK', ...res })
|
|
||||||
opStats.handle = process.hrtime.bigint()
|
|
||||||
callsMetrics.push({ ...opInfo, ...opStats, ...ctx })
|
|
||||||
}
|
|
||||||
break
|
|
||||||
case 'AuthorizeManage':
|
case 'AuthorizeManage':
|
||||||
if (!methods.AuthorizeManage) {
|
if (!methods.AuthorizeManage) {
|
||||||
throw new Error('method not defined: AuthorizeManage')
|
throw new Error('method not defined: AuthorizeManage')
|
||||||
|
|
|
||||||
|
|
@ -35,8 +35,8 @@ export type UserContext = {
|
||||||
app_user_id: string
|
app_user_id: string
|
||||||
user_id: string
|
user_id: string
|
||||||
}
|
}
|
||||||
export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeDebit_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | EnrollMessagingToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | ResetManage_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input
|
export type UserMethodInputs = AddProduct_Input | AddUserOffer_Input | AuthorizeManage_Input | BanDebit_Input | DecodeInvoice_Input | DeleteUserOffer_Input | EditDebit_Input | EnrollAdminToken_Input | EnrollMessagingToken_Input | GetDebitAuthorizations_Input | GetHttpCreds_Input | GetLNURLChannelLink_Input | GetLnurlPayLink_Input | GetLnurlWithdrawLink_Input | GetManageAuthorizations_Input | GetPaymentState_Input | GetUserInfo_Input | GetUserOffer_Input | GetUserOfferInvoices_Input | GetUserOffers_Input | GetUserOperations_Input | NewAddress_Input | NewInvoice_Input | NewProductInvoice_Input | PayAddress_Input | PayInvoice_Input | ResetDebit_Input | ResetManage_Input | RespondToDebit_Input | UpdateCallbackUrl_Input | UpdateUserOffer_Input | UserHealth_Input
|
||||||
export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeDebit_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | EnrollMessagingToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | ResetManage_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output
|
export type UserMethodOutputs = AddProduct_Output | AddUserOffer_Output | AuthorizeManage_Output | BanDebit_Output | DecodeInvoice_Output | DeleteUserOffer_Output | EditDebit_Output | EnrollAdminToken_Output | EnrollMessagingToken_Output | GetDebitAuthorizations_Output | GetHttpCreds_Output | GetLNURLChannelLink_Output | GetLnurlPayLink_Output | GetLnurlWithdrawLink_Output | GetManageAuthorizations_Output | GetPaymentState_Output | GetUserInfo_Output | GetUserOffer_Output | GetUserOfferInvoices_Output | GetUserOffers_Output | GetUserOperations_Output | NewAddress_Output | NewInvoice_Output | NewProductInvoice_Output | PayAddress_Output | PayInvoice_Output | ResetDebit_Output | ResetManage_Output | RespondToDebit_Output | UpdateCallbackUrl_Output | UpdateUserOffer_Output | UserHealth_Output
|
||||||
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
|
export type AuthContext = AdminContext | AppContext | GuestContext | GuestWithPubContext | MetricsContext | UserContext
|
||||||
|
|
||||||
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
|
export type AddApp_Input = {rpcName:'AddApp', req: AddAppRequest}
|
||||||
|
|
@ -63,9 +63,6 @@ export type AddUserOffer_Output = ResultError | ({ status: 'OK' } & OfferId)
|
||||||
export type AuthApp_Input = {rpcName:'AuthApp', req: AuthAppRequest}
|
export type AuthApp_Input = {rpcName:'AuthApp', req: AuthAppRequest}
|
||||||
export type AuthApp_Output = ResultError | ({ status: 'OK' } & AuthApp)
|
export type AuthApp_Output = ResultError | ({ status: 'OK' } & AuthApp)
|
||||||
|
|
||||||
export type AuthorizeDebit_Input = {rpcName:'AuthorizeDebit', req: DebitAuthorizationRequest}
|
|
||||||
export type AuthorizeDebit_Output = ResultError | ({ status: 'OK' } & DebitAuthorization)
|
|
||||||
|
|
||||||
export type AuthorizeManage_Input = {rpcName:'AuthorizeManage', req: ManageAuthorizationRequest}
|
export type AuthorizeManage_Input = {rpcName:'AuthorizeManage', req: ManageAuthorizationRequest}
|
||||||
export type AuthorizeManage_Output = ResultError | ({ status: 'OK' } & ManageAuthorization)
|
export type AuthorizeManage_Output = ResultError | ({ status: 'OK' } & ManageAuthorization)
|
||||||
|
|
||||||
|
|
@ -334,7 +331,6 @@ export type ServerMethods = {
|
||||||
AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise<Product>
|
AddProduct?: (req: AddProduct_Input & {ctx: UserContext }) => Promise<Product>
|
||||||
AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise<OfferId>
|
AddUserOffer?: (req: AddUserOffer_Input & {ctx: UserContext }) => Promise<OfferId>
|
||||||
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
|
AuthApp?: (req: AuthApp_Input & {ctx: AdminContext }) => Promise<AuthApp>
|
||||||
AuthorizeDebit?: (req: AuthorizeDebit_Input & {ctx: UserContext }) => Promise<DebitAuthorization>
|
|
||||||
AuthorizeManage?: (req: AuthorizeManage_Input & {ctx: UserContext }) => Promise<ManageAuthorization>
|
AuthorizeManage?: (req: AuthorizeManage_Input & {ctx: UserContext }) => Promise<ManageAuthorization>
|
||||||
BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void>
|
BanDebit?: (req: BanDebit_Input & {ctx: UserContext }) => Promise<void>
|
||||||
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
|
BanUser?: (req: BanUser_Input & {ctx: AdminContext }) => Promise<BanUserResponse>
|
||||||
|
|
@ -1435,6 +1431,35 @@ export const DebitRuleValidate = (o?: DebitRule, opts: DebitRuleOptions = {}, pa
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type DebitToAuthorize = {
|
||||||
|
invoice?: string
|
||||||
|
rules: DebitRule[]
|
||||||
|
}
|
||||||
|
export type DebitToAuthorizeOptionalField = 'invoice'
|
||||||
|
export const DebitToAuthorizeOptionalFields: DebitToAuthorizeOptionalField[] = ['invoice']
|
||||||
|
export type DebitToAuthorizeOptions = OptionsBaseMessage & {
|
||||||
|
checkOptionalsAreSet?: DebitToAuthorizeOptionalField[]
|
||||||
|
invoice_CustomCheck?: (v?: string) => boolean
|
||||||
|
rules_ItemOptions?: DebitRuleOptions
|
||||||
|
rules_CustomCheck?: (v: DebitRule[]) => boolean
|
||||||
|
}
|
||||||
|
export const DebitToAuthorizeValidate = (o?: DebitToAuthorize, opts: DebitToAuthorizeOptions = {}, path: string = 'DebitToAuthorize::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 ((o.invoice || opts.allOptionalsAreSet || opts.checkOptionalsAreSet?.includes('invoice')) && 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`)
|
||||||
|
|
||||||
|
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}]`)
|
||||||
|
if (rulesErr !== null) return rulesErr
|
||||||
|
}
|
||||||
|
if (opts.rules_CustomCheck && !opts.rules_CustomCheck(o.rules)) return new Error(`${path}.rules: custom check failed`)
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
export type DecodeInvoiceRequest = {
|
export type DecodeInvoiceRequest = {
|
||||||
invoice: string
|
invoice: string
|
||||||
}
|
}
|
||||||
|
|
@ -4211,6 +4236,7 @@ export const ZippedMetricsValidate = (o?: ZippedMetrics, opts: ZippedMetricsOpti
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum DebitResponse_response_type {
|
export enum DebitResponse_response_type {
|
||||||
|
AUTHORIZE = 'authorize',
|
||||||
DENIED = 'denied',
|
DENIED = 'denied',
|
||||||
INVOICE = 'invoice',
|
INVOICE = 'invoice',
|
||||||
}
|
}
|
||||||
|
|
@ -4219,10 +4245,12 @@ export const enumCheckDebitResponse_response_type = (e?: DebitResponse_response_
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
export type DebitResponse_response =
|
export type DebitResponse_response =
|
||||||
|
{type:DebitResponse_response_type.AUTHORIZE, authorize:DebitToAuthorize}|
|
||||||
{type:DebitResponse_response_type.DENIED, denied:Empty}|
|
{type:DebitResponse_response_type.DENIED, denied:Empty}|
|
||||||
{type:DebitResponse_response_type.INVOICE, invoice:string}
|
{type:DebitResponse_response_type.INVOICE, invoice:string}
|
||||||
|
|
||||||
export type DebitResponse_responseOptions = {
|
export type DebitResponse_responseOptions = {
|
||||||
|
authorize_Options?: DebitToAuthorizeOptions
|
||||||
denied_Options?: EmptyOptions
|
denied_Options?: EmptyOptions
|
||||||
invoice_CustomCheck?: (v: string) => boolean
|
invoice_CustomCheck?: (v: string) => boolean
|
||||||
}
|
}
|
||||||
|
|
@ -4230,6 +4258,12 @@ export const DebitResponse_responseValidate = (o?: DebitResponse_response, opts:
|
||||||
if (typeof o !== 'object' || o === null) return new Error(path + ': object is not an instance of an object or is 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
|
const stringType: string = o.type
|
||||||
switch (o.type) {
|
switch (o.type) {
|
||||||
|
case DebitResponse_response_type.AUTHORIZE:
|
||||||
|
const authorizeErr = DebitToAuthorizeValidate(o.authorize, opts.authorize_Options, `${path}.authorize`)
|
||||||
|
if (authorizeErr !== null) return authorizeErr
|
||||||
|
|
||||||
|
|
||||||
|
break
|
||||||
case DebitResponse_response_type.DENIED:
|
case DebitResponse_response_type.DENIED:
|
||||||
const deniedErr = EmptyValidate(o.denied, opts.denied_Options, `${path}.denied`)
|
const deniedErr = EmptyValidate(o.denied, opts.denied_Options, `${path}.denied`)
|
||||||
if (deniedErr !== null) return deniedErr
|
if (deniedErr !== null) return deniedErr
|
||||||
|
|
|
||||||
|
|
@ -610,12 +610,12 @@ service LightningPub {
|
||||||
option (http_route) = "/api/user/manage/reset";
|
option (http_route) = "/api/user/manage/reset";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
}
|
||||||
rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){
|
/* rpc AuthorizeDebit(structs.DebitAuthorizationRequest) returns (structs.DebitAuthorization){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
option (http_route) = "/api/user/debit/authorize";
|
option (http_route) = "/api/user/debit/authorize";
|
||||||
option (nostr) = true;
|
option (nostr) = true;
|
||||||
}
|
} */
|
||||||
rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){
|
rpc EditDebit(structs.DebitAuthorizationRequest) returns (structs.Empty){
|
||||||
option (auth_type) = "User";
|
option (auth_type) = "User";
|
||||||
option (http_method) = "post";
|
option (http_method) = "post";
|
||||||
|
|
|
||||||
|
|
@ -753,12 +753,18 @@ message LiveManageRequest {
|
||||||
string npub = 2;
|
string npub = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message DebitToAuthorize {
|
||||||
|
repeated DebitRule rules = 1;
|
||||||
|
optional string invoice = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message DebitResponse {
|
message DebitResponse {
|
||||||
string request_id = 1;
|
string request_id = 1;
|
||||||
string npub = 2;
|
string npub = 2;
|
||||||
oneof response {
|
oneof response {
|
||||||
Empty denied = 3;
|
Empty denied = 3;
|
||||||
string invoice = 4;
|
string invoice = 4;
|
||||||
|
DebitToAuthorize authorize = 5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,101 +8,11 @@ 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 { NostrEvent, NostrSend, SendData, SendInitiator } from '../nostr/handler.js';
|
||||||
import { UnsignedEvent } from 'nostr-tools';
|
import { UnsignedEvent } from 'nostr-tools';
|
||||||
import { NdebitData, NdebitFailure, NdebitSuccess, RecurringDebitTimeUnit } from "@shocknet/clink-sdk";
|
import { Ndebit, NdebitData, NdebitFailure, NdebitSuccess, RecurringDebitTimeUnit } from "@shocknet/clink-sdk";
|
||||||
|
import { debitAccessRulesToDebitRules, newNdebitResponse,debitRulesToDebitAccessRules,
|
||||||
|
nip68errs, AuthRequiredRes, HandleNdebitRes, expirationRuleName,
|
||||||
|
frequencyRuleName,IntervalTypeToSeconds,unitToIntervalType } from "./debitTypes.js";
|
||||||
|
|
||||||
export const expirationRuleName = 'expiration'
|
|
||||||
export const frequencyRuleName = 'frequency'
|
|
||||||
const unitToIntervalType = (unit: RecurringDebitTimeUnit) => {
|
|
||||||
switch (unit) {
|
|
||||||
case 'day': return Types.IntervalType.DAY
|
|
||||||
case 'week': return Types.IntervalType.WEEK
|
|
||||||
case 'month': return Types.IntervalType.MONTH
|
|
||||||
default: throw new Error("invalid unit")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const intervalTypeToUnit = (interval: Types.IntervalType): RecurringDebitTimeUnit => {
|
|
||||||
switch (interval) {
|
|
||||||
case Types.IntervalType.DAY: return 'day'
|
|
||||||
case Types.IntervalType.WEEK: return 'week'
|
|
||||||
case Types.IntervalType.MONTH: return 'month'
|
|
||||||
default: throw new Error("invalid interval")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const IntervalTypeToSeconds = (interval: Types.IntervalType) => {
|
|
||||||
switch (interval) {
|
|
||||||
case Types.IntervalType.DAY: return 24 * 60 * 60
|
|
||||||
case Types.IntervalType.WEEK: return 7 * 24 * 60 * 60
|
|
||||||
case Types.IntervalType.MONTH: return 30 * 24 * 60 * 60
|
|
||||||
default: throw new Error("invalid interval")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const debitRulesToDebitAccessRules = (rule: Types.DebitRule[]): DebitAccessRules | undefined => {
|
|
||||||
let rules: DebitAccessRules | undefined = undefined
|
|
||||||
rule.forEach(r => {
|
|
||||||
if (!rules) {
|
|
||||||
rules = {}
|
|
||||||
}
|
|
||||||
const { rule } = r
|
|
||||||
switch (rule.type) {
|
|
||||||
case Types.DebitRule_rule_type.EXPIRATION_RULE:
|
|
||||||
|
|
||||||
rules[expirationRuleName] = [rule.expiration_rule.expires_at_unix.toString()]
|
|
||||||
break
|
|
||||||
case Types.DebitRule_rule_type.FREQUENCY_RULE:
|
|
||||||
const intervals = rule.frequency_rule.number_of_intervals.toString()
|
|
||||||
const unit = intervalTypeToUnit(rule.frequency_rule.interval)
|
|
||||||
rules[frequencyRuleName] = [intervals, unit, rule.frequency_rule.amount.toString()];
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
throw new Error("invalid rule")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return rules
|
|
||||||
}
|
|
||||||
|
|
||||||
const debitAccessRulesToDebitRules = (rules: DebitAccessRules | null): Types.DebitRule[] => {
|
|
||||||
if (!rules) {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
return Object.entries(rules).map(([key, val]) => {
|
|
||||||
switch (key) {
|
|
||||||
case expirationRuleName:
|
|
||||||
return {
|
|
||||||
rule: {
|
|
||||||
type: Types.DebitRule_rule_type.EXPIRATION_RULE,
|
|
||||||
expiration_rule: {
|
|
||||||
expires_at_unix: +val[0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case frequencyRuleName:
|
|
||||||
return {
|
|
||||||
rule: {
|
|
||||||
type: Types.DebitRule_rule_type.FREQUENCY_RULE,
|
|
||||||
frequency_rule: {
|
|
||||||
number_of_intervals: +val[0],
|
|
||||||
interval: unitToIntervalType(val[1] as RecurringDebitTimeUnit),
|
|
||||||
amount: +val[2]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
throw new Error("invalid rule")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
const nip68errs = {
|
|
||||||
1: "Request Denied Warning",
|
|
||||||
2: "Temporary Failure",
|
|
||||||
3: "Expired Request",
|
|
||||||
4: "Rate Limited",
|
|
||||||
5: "Invalid Amount",
|
|
||||||
6: "Invalid Request",
|
|
||||||
}
|
|
||||||
type HandleNdebitRes = { status: 'fail', debitRes: NdebitFailure }
|
|
||||||
| { status: 'invoicePaid', op: Types.UserOperation, app: Application, appUser: ApplicationUser, debitRes: NdebitSuccess }
|
|
||||||
| { status: 'authRequired', liveDebitReq: Types.LiveDebitRequest, app: Application, appUser: ApplicationUser }
|
|
||||||
| { status: 'authOk', debitRes: NdebitSuccess }
|
|
||||||
export class DebitManager {
|
export class DebitManager {
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -129,7 +39,7 @@ export class DebitManager {
|
||||||
this._nostrSend(initiator, data, relays)
|
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,
|
||||||
|
|
@ -144,7 +54,7 @@ export class DebitManager {
|
||||||
authorized: true,
|
authorized: true,
|
||||||
rules: req.rules
|
rules: req.rules
|
||||||
}
|
}
|
||||||
}
|
} */
|
||||||
|
|
||||||
GetDebitAuthorizations = async (ctx: Types.UserContext): Promise<Types.DebitAuthorizations> => {
|
GetDebitAuthorizations = async (ctx: Types.UserContext): Promise<Types.DebitAuthorizations> => {
|
||||||
const allDebitsAccesses = await this.storage.debitStorage.GetAllUserDebitAccess(ctx.app_user_id)
|
const allDebitsAccesses = await this.storage.debitStorage.GetAllUserDebitAccess(ctx.app_user_id)
|
||||||
|
|
@ -178,17 +88,58 @@ export class DebitManager {
|
||||||
this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: req.npub, id: req.request_id, appId: ctx.app_id })
|
this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: req.npub, id: req.request_id, appId: ctx.app_id })
|
||||||
return
|
return
|
||||||
case Types.DebitResponse_response_type.INVOICE:
|
case Types.DebitResponse_response_type.INVOICE:
|
||||||
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
|
await this.paySingleInvoice(ctx, {invoice: req.response.invoice, npub: req.npub, request_id: req.request_id})
|
||||||
const appUser = await this.storage.applicationStorage.GetApplicationUser(app, ctx.app_user_id)
|
return
|
||||||
const { op, payment } = await this.sendDebitPayment(ctx.app_id, ctx.app_user_id, req.npub, req.response.invoice)
|
case Types.DebitResponse_response_type.AUTHORIZE:
|
||||||
const debitRes: NdebitSuccess = { res: 'ok', preimage: payment.preimage }
|
await this.handleAuthorization(ctx, req.response.authorize, { npub: req.npub, request_id: req.request_id })
|
||||||
this.notifyPaymentSuccess(appUser, debitRes, op, { appId: ctx.app_id, pub: req.npub, id: req.request_id })
|
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
throw new Error("invalid debit response type")
|
throw new Error("invalid debit response type")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
paySingleInvoice = async (ctx: Types.UserContext, {invoice,npub,request_id}:{invoice:string, npub:string, request_id:string}) => {
|
||||||
|
try {
|
||||||
|
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, npub, invoice)
|
||||||
|
const debitRes: NdebitSuccess = { res: 'ok', preimage: payment.preimage }
|
||||||
|
this.notifyPaymentSuccess(appUser, debitRes, op, { appId: ctx.app_id, pub: npub, id: request_id })
|
||||||
|
} catch (e: any) {
|
||||||
|
this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: npub, id: request_id, appId: ctx.app_id })
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
handleAuthorization = async(ctx: Types.UserContext,debit:Types.DebitToAuthorize, {npub,request_id}:{ npub:string, request_id:string})=>{
|
||||||
|
const access = await this.storage.debitStorage.AddDebitAccess(ctx.app_user_id, {
|
||||||
|
authorize: true,
|
||||||
|
npub,
|
||||||
|
rules: debitRulesToDebitAccessRules(debit.rules)
|
||||||
|
})
|
||||||
|
const { invoice } = debit
|
||||||
|
if (!request_id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!invoice) {
|
||||||
|
this.sendDebitResponse({ res: 'ok' }, { pub: npub, id: request_id, appId: ctx.app_id })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const app = await this.storage.applicationStorage.GetApplication(ctx.app_id)
|
||||||
|
const appUser = await this.storage.applicationStorage.GetApplicationUser(app, ctx.app_user_id)
|
||||||
|
this.validateAccessRules(access, app, appUser)
|
||||||
|
const { op, payment } = await this.sendDebitPayment(ctx.app_id, ctx.app_user_id, npub, invoice)
|
||||||
|
const debitRes: NdebitSuccess = { res: 'ok', preimage: payment.preimage }
|
||||||
|
this.notifyPaymentSuccess(appUser, debitRes, op, { appId: ctx.app_id, pub: npub, id: request_id })
|
||||||
|
} catch (e: any) {
|
||||||
|
this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: npub, id: request_id, appId: ctx.app_id })
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
handleNip68Debit = async (pointerdata: NdebitData, event: NostrEvent) => {
|
handleNip68Debit = async (pointerdata: NdebitData, event: NostrEvent) => {
|
||||||
if (!this._nostrSend) {
|
if (!this._nostrSend) {
|
||||||
throw new Error("No nostrSend attached")
|
throw new Error("No nostrSend attached")
|
||||||
|
|
@ -201,16 +152,22 @@ export class DebitManager {
|
||||||
}
|
}
|
||||||
const { appUser } = res
|
const { appUser } = res
|
||||||
if (res.status === 'authRequired') {
|
if (res.status === 'authRequired') {
|
||||||
const message: Types.LiveDebitRequest & { requestId: string, status: 'OK' } = { ...res.liveDebitReq, requestId: "GetLiveDebitRequests", status: 'OK' }
|
this.handleAuthRequired(pointerdata, event, res)
|
||||||
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
|
return
|
||||||
}
|
}
|
||||||
const { op, debitRes } = res
|
const { op, debitRes } = res
|
||||||
this.notifyPaymentSuccess(appUser, debitRes, op, event)
|
this.notifyPaymentSuccess(appUser, debitRes, op, event)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
handleAuthRequired = (data:NdebitData, event: NostrEvent, res: AuthRequiredRes) => {
|
||||||
|
if (!res.appUser.nostr_public_key) {
|
||||||
|
this.sendDebitResponse({ res: 'GFY', error: nip68errs[1], code: 1 }, { pub: event.pub, id: event.id, appId: event.appId })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const message: Types.LiveDebitRequest & { requestId: string, status: 'OK' } = { ...res.liveDebitReq, requestId: "GetLiveDebitRequests", status: 'OK' }
|
||||||
|
this.nostrSend({ type: 'app', appId: event.appId }, { type: 'content', content: JSON.stringify(message), pub: res.appUser.nostr_public_key })
|
||||||
|
}
|
||||||
|
|
||||||
notifyPaymentSuccess = (appUser: ApplicationUser, debitRes: NdebitSuccess, op: Types.UserOperation, event: { pub: string, id: string, appId: string }) => {
|
notifyPaymentSuccess = (appUser: ApplicationUser, debitRes: NdebitSuccess, op: Types.UserOperation, event: { pub: string, id: string, appId: string }) => {
|
||||||
const message: Types.LiveUserOperation & { requestId: string, status: 'OK' } = { operation: op, requestId: "GetLiveUserOperations", status: 'OK' }
|
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
|
if (appUser.nostr_public_key) { // TODO - fix before support for http streams
|
||||||
|
|
@ -378,15 +335,3 @@ 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],
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
114
src/services/main/debitTypes.ts
Normal file
114
src/services/main/debitTypes.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
import * as Types from "../../../proto/autogenerated/ts/types.js";
|
||||||
|
import { DebitAccessRules } from '../storage/entity/DebitAccess.js';
|
||||||
|
import { Application } from '../storage/entity/Application.js';
|
||||||
|
import { ApplicationUser } from '../storage/entity/ApplicationUser.js';
|
||||||
|
import { UnsignedEvent } from 'nostr-tools';
|
||||||
|
import { NdebitFailure, NdebitSuccess, RecurringDebitTimeUnit } from "@shocknet/clink-sdk";
|
||||||
|
|
||||||
|
export const expirationRuleName = 'expiration'
|
||||||
|
export const frequencyRuleName = 'frequency'
|
||||||
|
export const unitToIntervalType = (unit: RecurringDebitTimeUnit) => {
|
||||||
|
switch (unit) {
|
||||||
|
case 'day': return Types.IntervalType.DAY
|
||||||
|
case 'week': return Types.IntervalType.WEEK
|
||||||
|
case 'month': return Types.IntervalType.MONTH
|
||||||
|
default: throw new Error("invalid unit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const intervalTypeToUnit = (interval: Types.IntervalType): RecurringDebitTimeUnit => {
|
||||||
|
switch (interval) {
|
||||||
|
case Types.IntervalType.DAY: return 'day'
|
||||||
|
case Types.IntervalType.WEEK: return 'week'
|
||||||
|
case Types.IntervalType.MONTH: return 'month'
|
||||||
|
default: throw new Error("invalid interval")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export const IntervalTypeToSeconds = (interval: Types.IntervalType) => {
|
||||||
|
switch (interval) {
|
||||||
|
case Types.IntervalType.DAY: return 24 * 60 * 60
|
||||||
|
case Types.IntervalType.WEEK: return 7 * 24 * 60 * 60
|
||||||
|
case Types.IntervalType.MONTH: return 30 * 24 * 60 * 60
|
||||||
|
default: throw new Error("invalid interval")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export const debitRulesToDebitAccessRules = (rule: Types.DebitRule[]): DebitAccessRules | undefined => {
|
||||||
|
let rules: DebitAccessRules | undefined = undefined
|
||||||
|
rule.forEach(r => {
|
||||||
|
if (!rules) {
|
||||||
|
rules = {}
|
||||||
|
}
|
||||||
|
const { rule } = r
|
||||||
|
switch (rule.type) {
|
||||||
|
case Types.DebitRule_rule_type.EXPIRATION_RULE:
|
||||||
|
|
||||||
|
rules[expirationRuleName] = [rule.expiration_rule.expires_at_unix.toString()]
|
||||||
|
break
|
||||||
|
case Types.DebitRule_rule_type.FREQUENCY_RULE:
|
||||||
|
const intervals = rule.frequency_rule.number_of_intervals.toString()
|
||||||
|
const unit = intervalTypeToUnit(rule.frequency_rule.interval)
|
||||||
|
rules[frequencyRuleName] = [intervals, unit, rule.frequency_rule.amount.toString()];
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
throw new Error("invalid rule")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return rules
|
||||||
|
}
|
||||||
|
|
||||||
|
export const debitAccessRulesToDebitRules = (rules: DebitAccessRules | null): Types.DebitRule[] => {
|
||||||
|
if (!rules) {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
return Object.entries(rules).map(([key, val]) => {
|
||||||
|
switch (key) {
|
||||||
|
case expirationRuleName:
|
||||||
|
return {
|
||||||
|
rule: {
|
||||||
|
type: Types.DebitRule_rule_type.EXPIRATION_RULE,
|
||||||
|
expiration_rule: {
|
||||||
|
expires_at_unix: +val[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case frequencyRuleName:
|
||||||
|
return {
|
||||||
|
rule: {
|
||||||
|
type: Types.DebitRule_rule_type.FREQUENCY_RULE,
|
||||||
|
frequency_rule: {
|
||||||
|
number_of_intervals: +val[0],
|
||||||
|
interval: unitToIntervalType(val[1] as RecurringDebitTimeUnit),
|
||||||
|
amount: +val[2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error("invalid rule")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
export const nip68errs = {
|
||||||
|
1: "Request Denied Warning",
|
||||||
|
2: "Temporary Failure",
|
||||||
|
3: "Expired Request",
|
||||||
|
4: "Rate Limited",
|
||||||
|
5: "Invalid Amount",
|
||||||
|
6: "Invalid Request",
|
||||||
|
}
|
||||||
|
export type AuthRequiredRes = { status: 'authRequired', liveDebitReq: Types.LiveDebitRequest, app: Application, appUser: ApplicationUser }
|
||||||
|
export type HandleNdebitRes = { status: 'fail', debitRes: NdebitFailure }
|
||||||
|
| { status: 'invoicePaid', op: Types.UserOperation, app: Application, appUser: ApplicationUser, debitRes: NdebitSuccess }
|
||||||
|
| AuthRequiredRes
|
||||||
|
| { status: 'authOk', debitRes: NdebitSuccess }
|
||||||
|
|
||||||
|
export 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],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue