@owlmeans/server-payment 0.1.20-rc.1 → 0.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/README.md +52 -54
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +272 -330
  4. package/agent-meta/skills/server-payment/parts/reference.md +3 -3
  5. package/build/access/types.d.ts +7 -16
  6. package/build/access/types.d.ts.map +1 -1
  7. package/build/access.d.ts.map +1 -1
  8. package/build/access.js +6 -8
  9. package/build/access.js.map +1 -1
  10. package/build/actions/resync.d.ts +3 -3
  11. package/build/actions/resync.js +5 -5
  12. package/build/actions/resync.js.map +1 -1
  13. package/build/actions/webhook.d.ts +4 -1
  14. package/build/actions/webhook.d.ts.map +1 -1
  15. package/build/actions/webhook.js +8 -4
  16. package/build/actions/webhook.js.map +1 -1
  17. package/build/bootstrap/types.d.ts +13 -7
  18. package/build/bootstrap/types.d.ts.map +1 -1
  19. package/build/bootstrap.d.ts +4 -4
  20. package/build/bootstrap.d.ts.map +1 -1
  21. package/build/bootstrap.js +19 -10
  22. package/build/bootstrap.js.map +1 -1
  23. package/build/catalogue/types.d.ts +3 -3
  24. package/build/catalogue/types.d.ts.map +1 -1
  25. package/build/catalogue.d.ts.map +1 -1
  26. package/build/catalogue.js +4 -8
  27. package/build/catalogue.js.map +1 -1
  28. package/build/checkout/types.d.ts +21 -0
  29. package/build/checkout/types.d.ts.map +1 -0
  30. package/build/{plugins/stripe → checkout}/types.js.map +1 -1
  31. package/build/checkout.d.ts +6 -0
  32. package/build/checkout.d.ts.map +1 -0
  33. package/build/checkout.js +374 -0
  34. package/build/checkout.js.map +1 -0
  35. package/build/config.d.ts +10 -16
  36. package/build/config.d.ts.map +1 -1
  37. package/build/config.js +18 -59
  38. package/build/config.js.map +1 -1
  39. package/build/consts.d.ts +3 -49
  40. package/build/consts.d.ts.map +1 -1
  41. package/build/consts.js +3 -61
  42. package/build/consts.js.map +1 -1
  43. package/build/consumer/cancellation/types.d.ts +6 -4
  44. package/build/consumer/cancellation/types.d.ts.map +1 -1
  45. package/build/consumer/cancellation.d.ts.map +1 -1
  46. package/build/consumer/cancellation.js +11 -5
  47. package/build/consumer/cancellation.js.map +1 -1
  48. package/build/consumer/capture/types.d.ts +8 -12
  49. package/build/consumer/capture/types.d.ts.map +1 -1
  50. package/build/consumer/capture.d.ts.map +1 -1
  51. package/build/consumer/capture.js +48 -53
  52. package/build/consumer/capture.js.map +1 -1
  53. package/build/consumer/index.d.ts +4 -0
  54. package/build/consumer/index.d.ts.map +1 -1
  55. package/build/consumer/index.js +2 -0
  56. package/build/consumer/index.js.map +1 -1
  57. package/build/consumer/reconcile.d.ts.map +1 -1
  58. package/build/consumer/reconcile.js +82 -72
  59. package/build/consumer/reconcile.js.map +1 -1
  60. package/build/consumer/records/types.d.ts +4 -4
  61. package/build/consumer/records/types.d.ts.map +1 -1
  62. package/build/consumer/records.d.ts.map +1 -1
  63. package/build/consumer/records.js +16 -13
  64. package/build/consumer/records.js.map +1 -1
  65. package/build/consumer/service.d.ts +2 -2
  66. package/build/consumer/service.d.ts.map +1 -1
  67. package/build/consumer/service.js +28 -21
  68. package/build/consumer/service.js.map +1 -1
  69. package/build/consumer/types.d.ts +1 -4
  70. package/build/consumer/types.d.ts.map +1 -1
  71. package/build/consumer/types.local.d.ts +1 -9
  72. package/build/consumer/types.local.d.ts.map +1 -1
  73. package/build/consumer/withdrawal/types.d.ts +14 -12
  74. package/build/consumer/withdrawal/types.d.ts.map +1 -1
  75. package/build/consumer/withdrawal.d.ts.map +1 -1
  76. package/build/consumer/withdrawal.js +55 -71
  77. package/build/consumer/withdrawal.js.map +1 -1
  78. package/build/index.d.ts +12 -6
  79. package/build/index.d.ts.map +1 -1
  80. package/build/index.js +7 -4
  81. package/build/index.js.map +1 -1
  82. package/build/paygate/providers.d.ts +13 -0
  83. package/build/paygate/providers.d.ts.map +1 -0
  84. package/build/paygate/providers.js +38 -0
  85. package/build/paygate/providers.js.map +1 -0
  86. package/build/paygate/registry.d.ts +6 -0
  87. package/build/paygate/registry.d.ts.map +1 -0
  88. package/build/paygate/registry.js +37 -0
  89. package/build/paygate/registry.js.map +1 -0
  90. package/build/paygate/types.d.ts +577 -0
  91. package/build/paygate/types.d.ts.map +1 -0
  92. package/build/{plugins/session → paygate}/types.js.map +1 -1
  93. package/build/plan/types.d.ts +6 -1
  94. package/build/plan/types.d.ts.map +1 -1
  95. package/build/plan.d.ts.map +1 -1
  96. package/build/plan.js +16 -2
  97. package/build/plan.js.map +1 -1
  98. package/build/plugins/checkout-policy/types.d.ts +5 -3
  99. package/build/plugins/checkout-policy/types.d.ts.map +1 -1
  100. package/build/plugins/checkout-policy.d.ts.map +1 -1
  101. package/build/plugins/checkout-policy.js +5 -3
  102. package/build/plugins/checkout-policy.js.map +1 -1
  103. package/build/plugins/consts.local.d.ts +8 -10
  104. package/build/plugins/consts.local.d.ts.map +1 -1
  105. package/build/plugins/consts.local.js +2 -19
  106. package/build/plugins/consts.local.js.map +1 -1
  107. package/build/plugins/customer-lock/types.d.ts +2 -2
  108. package/build/plugins/customer-lock/types.d.ts.map +1 -1
  109. package/build/plugins/customer-lock.js +2 -2
  110. package/build/plugins/customer-lock.js.map +1 -1
  111. package/build/plugins/estimate/cache.js +1 -1
  112. package/build/plugins/estimate/cache.js.map +1 -1
  113. package/build/plugins/estimate/types.d.ts +10 -10
  114. package/build/plugins/estimate/types.d.ts.map +1 -1
  115. package/build/plugins/estimate.d.ts.map +1 -1
  116. package/build/plugins/estimate.js +48 -122
  117. package/build/plugins/estimate.js.map +1 -1
  118. package/build/plugins/events/types.d.ts +17 -10
  119. package/build/plugins/events/types.d.ts.map +1 -1
  120. package/build/plugins/events.d.ts +6 -5
  121. package/build/plugins/events.d.ts.map +1 -1
  122. package/build/plugins/events.js +162 -173
  123. package/build/plugins/events.js.map +1 -1
  124. package/build/plugins/fx/types.d.ts +10 -21
  125. package/build/plugins/fx/types.d.ts.map +1 -1
  126. package/build/plugins/fx.d.ts +1 -1
  127. package/build/plugins/fx.d.ts.map +1 -1
  128. package/build/plugins/fx.js +17 -54
  129. package/build/plugins/fx.js.map +1 -1
  130. package/build/plugins/portal/types.d.ts +8 -37
  131. package/build/plugins/portal/types.d.ts.map +1 -1
  132. package/build/plugins/portal.d.ts.map +1 -1
  133. package/build/plugins/portal.js +38 -208
  134. package/build/plugins/portal.js.map +1 -1
  135. package/build/plugins/refunds/types.d.ts +11 -11
  136. package/build/plugins/refunds/types.d.ts.map +1 -1
  137. package/build/plugins/refunds.d.ts.map +1 -1
  138. package/build/plugins/refunds.js +14 -39
  139. package/build/plugins/refunds.js.map +1 -1
  140. package/build/plugins/snapshot/types.d.ts +11 -0
  141. package/build/plugins/snapshot/types.d.ts.map +1 -0
  142. package/build/plugins/snapshot/types.js +2 -0
  143. package/build/plugins/snapshot/types.js.map +1 -0
  144. package/build/plugins/snapshot.d.ts +4 -0
  145. package/build/plugins/snapshot.d.ts.map +1 -0
  146. package/build/plugins/snapshot.js +19 -0
  147. package/build/plugins/snapshot.js.map +1 -0
  148. package/build/plugins/subscriptions/types.d.ts +17 -17
  149. package/build/plugins/subscriptions/types.d.ts.map +1 -1
  150. package/build/plugins/subscriptions.d.ts +4 -4
  151. package/build/plugins/subscriptions.d.ts.map +1 -1
  152. package/build/plugins/subscriptions.js +69 -77
  153. package/build/plugins/subscriptions.js.map +1 -1
  154. package/build/plugins/types.local.d.ts +9 -43
  155. package/build/plugins/types.local.d.ts.map +1 -1
  156. package/build/plugins/webhook-manager/types.d.ts +15 -43
  157. package/build/plugins/webhook-manager/types.d.ts.map +1 -1
  158. package/build/plugins/webhook-manager.d.ts +3 -3
  159. package/build/plugins/webhook-manager.d.ts.map +1 -1
  160. package/build/plugins/webhook-manager.js +21 -199
  161. package/build/plugins/webhook-manager.js.map +1 -1
  162. package/build/protocol.d.ts +1 -1
  163. package/build/protocol.d.ts.map +1 -1
  164. package/build/protocol.js +1 -1
  165. package/build/protocol.js.map +1 -1
  166. package/build/service.d.ts +11 -11
  167. package/build/service.d.ts.map +1 -1
  168. package/build/service.js +59 -23
  169. package/build/service.js.map +1 -1
  170. package/build/sync/types.d.ts +17 -13
  171. package/build/sync/types.d.ts.map +1 -1
  172. package/build/sync.d.ts.map +1 -1
  173. package/build/sync.js +22 -122
  174. package/build/sync.js.map +1 -1
  175. package/build/types.d.ts +46 -101
  176. package/build/types.d.ts.map +1 -1
  177. package/build/utils/types.d.ts +0 -8
  178. package/build/utils/types.d.ts.map +1 -1
  179. package/build/utils.d.ts +1 -4
  180. package/build/utils.d.ts.map +1 -1
  181. package/build/utils.js +1 -15
  182. package/build/utils.js.map +1 -1
  183. package/package.json +20 -22
  184. package/src/access/types.ts +7 -16
  185. package/src/access.ts +7 -15
  186. package/src/actions/resync.ts +5 -5
  187. package/src/actions/webhook.ts +8 -4
  188. package/src/bootstrap/types.ts +13 -7
  189. package/src/bootstrap.ts +23 -13
  190. package/src/catalogue/types.ts +3 -3
  191. package/src/catalogue.ts +4 -8
  192. package/src/checkout/types.ts +21 -0
  193. package/src/checkout.ts +414 -0
  194. package/src/config.ts +19 -66
  195. package/src/consts.ts +3 -69
  196. package/src/consumer/cancellation/types.ts +6 -4
  197. package/src/consumer/cancellation.ts +13 -7
  198. package/src/consumer/capture/types.ts +8 -12
  199. package/src/consumer/capture.ts +50 -59
  200. package/src/consumer/index.ts +4 -0
  201. package/src/consumer/reconcile.ts +69 -68
  202. package/src/consumer/records/types.ts +4 -4
  203. package/src/consumer/records.ts +19 -14
  204. package/src/consumer/service.ts +35 -22
  205. package/src/consumer/types.local.ts +1 -8
  206. package/src/consumer/types.ts +1 -4
  207. package/src/consumer/withdrawal/types.ts +14 -12
  208. package/src/consumer/withdrawal.ts +61 -77
  209. package/src/index.ts +12 -6
  210. package/src/paygate/providers.ts +48 -0
  211. package/src/paygate/registry.ts +53 -0
  212. package/src/paygate/types.ts +640 -0
  213. package/src/plan/types.ts +6 -1
  214. package/src/plan.ts +21 -3
  215. package/src/plugins/checkout-policy/types.ts +5 -3
  216. package/src/plugins/checkout-policy.ts +6 -5
  217. package/src/plugins/consts.local.ts +2 -26
  218. package/src/plugins/customer-lock/types.ts +2 -2
  219. package/src/plugins/customer-lock.ts +2 -2
  220. package/src/plugins/estimate/cache.ts +1 -1
  221. package/src/plugins/estimate/types.ts +10 -10
  222. package/src/plugins/estimate.ts +52 -128
  223. package/src/plugins/events/types.ts +17 -9
  224. package/src/plugins/events.ts +172 -190
  225. package/src/plugins/fx/types.ts +10 -23
  226. package/src/plugins/fx.ts +28 -64
  227. package/src/plugins/portal/types.ts +8 -38
  228. package/src/plugins/portal.ts +48 -229
  229. package/src/plugins/refunds/types.ts +11 -11
  230. package/src/plugins/refunds.ts +16 -40
  231. package/src/plugins/snapshot/types.ts +11 -0
  232. package/src/plugins/snapshot.ts +22 -0
  233. package/src/plugins/subscriptions/types.ts +17 -17
  234. package/src/plugins/subscriptions.ts +81 -81
  235. package/src/plugins/types.local.ts +9 -33
  236. package/src/plugins/webhook-manager/types.ts +15 -43
  237. package/src/plugins/webhook-manager.ts +24 -220
  238. package/src/protocol.ts +1 -1
  239. package/src/service.ts +66 -30
  240. package/src/sync/types.ts +17 -13
  241. package/src/sync.ts +25 -143
  242. package/src/types.ts +47 -97
  243. package/src/utils/types.ts +0 -9
  244. package/src/utils.ts +2 -20
  245. package/tests/capabilities.spec.ts +219 -0
  246. package/tests/entitlement.spec.ts +4 -4
  247. package/tests/gate-handlers.spec.ts +6 -6
  248. package/tests/gate.spec.ts +2 -2
  249. package/tests/grants.spec.ts +2 -2
  250. package/tests/internal-plan.spec.ts +2 -2
  251. package/tests/limit-gate.spec.ts +2 -2
  252. package/tests/paygates.spec.ts +132 -0
  253. package/tests/protocol.spec.ts +4 -5
  254. package/tests/usage.spec.ts +2 -2
  255. package/tests/webhook.spec.ts +137 -0
  256. package/build/plugins/session/types.d.ts +0 -34
  257. package/build/plugins/session/types.d.ts.map +0 -1
  258. package/build/plugins/session.d.ts +0 -4
  259. package/build/plugins/session.d.ts.map +0 -1
  260. package/build/plugins/session.js +0 -71
  261. package/build/plugins/session.js.map +0 -1
  262. package/build/plugins/status.d.ts +0 -8
  263. package/build/plugins/status.d.ts.map +0 -1
  264. package/build/plugins/status.js +0 -21
  265. package/build/plugins/status.js.map +0 -1
  266. package/build/plugins/stripe/types.d.ts +0 -20
  267. package/build/plugins/stripe/types.d.ts.map +0 -1
  268. package/build/plugins/stripe.d.ts +0 -6
  269. package/build/plugins/stripe.d.ts.map +0 -1
  270. package/build/plugins/stripe.js +0 -518
  271. package/build/plugins/stripe.js.map +0 -1
  272. package/src/plugins/session/types.ts +0 -30
  273. package/src/plugins/session.ts +0 -86
  274. package/src/plugins/status.ts +0 -22
  275. package/src/plugins/stripe/types.ts +0 -20
  276. package/src/plugins/stripe.ts +0 -571
  277. package/tests/checkout-consumer.spec.ts +0 -366
  278. package/tests/checkout-locks.spec.ts +0 -161
  279. package/tests/checkout-plugins.spec.ts +0 -164
  280. package/tests/checkout.spec.ts +0 -313
  281. package/tests/consumer-events.spec.ts +0 -215
  282. package/tests/consumer-fixtures.ts +0 -141
  283. package/tests/consumer-ops.spec.ts +0 -361
  284. package/tests/consumer-rights.integration.spec.ts +0 -147
  285. package/tests/consumer-rights.spec.ts +0 -606
  286. package/tests/context.ts +0 -110
  287. package/tests/estimate.spec.ts +0 -350
  288. package/tests/events.spec.ts +0 -367
  289. package/tests/fake-stripe.ts +0 -1004
  290. package/tests/gateway-options.spec.ts +0 -180
  291. package/tests/portal.spec.ts +0 -202
  292. package/tests/sync.spec.ts +0 -114
  293. package/tests/usage.integration.spec.ts +0 -165
  294. package/tests/webhook-manager.spec.ts +0 -149
  295. /package/build/{plugins/session → checkout}/types.js +0 -0
  296. /package/build/{plugins/stripe → paygate}/types.js +0 -0
@@ -1,20 +1,15 @@
1
- import { createHash } from 'node:crypto'
2
- import type Stripe from 'stripe'
3
1
  import { makeSecurityHelper } from '@owlmeans/config'
4
2
  import { type CommonServiceRoute, normalizePath } from '@owlmeans/route'
5
- import { WebhookSetupError, PaygateSignatureError } from '@owlmeans/payment'
3
+ import { PaygateError, WebhookSetupError } from '@owlmeans/payment'
6
4
  import type { Context as ApiContext } from '@owlmeans/server-api'
7
5
  import { memoHelper } from '@owlmeans/context'
8
- import {
9
- STRIPE_OWNER_KEY, STRIPE_OWNER_VALUE, STRIPE_PAYGATE_ALIAS, WEBHOOK_EVENTS, STRIPE_SIGNATURE,
10
- } from '../consts.js'
11
6
  import type { PaymentWebhookRecord } from '../types.js'
7
+ import type { Paygate, PaygateDeployment } from '../paygate/types.js'
12
8
  import { log } from '../log.js'
13
9
  import type { EnsureWebhookOptions, WebhookHelper } from './webhook-manager/types.js'
14
10
  import { paymentAccessOf } from '../access.js'
15
- import { paymentUtils } from '../utils.js'
16
11
  import { paymentGate } from '../protocol.js'
17
- import { createEventHandler } from './events.js'
12
+ import { paymentEventsOf } from './events.js'
18
13
  import type { WebhookRequest } from './types.local.js'
19
14
 
20
15
  /** The path the webhook route answers for one paygate: `/<base>/webhook/<paygate>`. */
@@ -36,13 +31,6 @@ const isDeliverableUrl = (url: string): boolean => {
36
31
  && !host.endsWith('.local') && host.includes('.')
37
32
  }
38
33
 
39
- /** An operator's label on an endpoint this package created — never evidence of which deployment owns it. */
40
- const ownerMetadata = (owner: string): Record<string, string> =>
41
- ({ [STRIPE_OWNER_KEY]: STRIPE_OWNER_VALUE, service: owner })
42
-
43
- const hashOf = (url: string, apiVersion: string, events: string[]): string =>
44
- createHash('sha256').update(JSON.stringify({ url, apiVersion, events })).digest('hex')
45
-
46
34
  export const makeWebhookHelper = (ctx: ApiContext): WebhookHelper => {
47
35
  const access = paymentAccessOf(ctx)
48
36
 
@@ -59,230 +47,46 @@ export const makeWebhookHelper = (ctx: ApiContext): WebhookHelper => {
59
47
  return route
60
48
  }
61
49
 
62
- const webhookUrlOf = (paygate: string = STRIPE_PAYGATE_ALIAS): string =>
50
+ const webhookUrlOf = (paygate: string): string =>
63
51
  makeSecurityHelper(ctx as never).makeUrl(webhookRouteOf(), webhookPathOf(paygate))
64
52
 
65
- const listEndpoints = async (stripe: Stripe): Promise<Stripe.WebhookEndpoint[]> => {
66
- const endpoints: Stripe.WebhookEndpoint[] = []
67
- let startingAfter: string | undefined
68
- for (;;) {
69
- const page = await stripe.webhookEndpoints.list({
70
- limit: 100, ...(startingAfter != null ? { starting_after: startingAfter } : {}),
71
- })
72
- endpoints.push(...page.data)
73
- if (!page.has_more || page.data.length === 0) {
74
- return endpoints
75
- }
76
- startingAfter = page.data[page.data.length - 1].id
77
- }
78
- }
79
-
80
- const dropEndpoint = async (stripe: Stripe, id: string): Promise<void> => {
81
- try {
82
- await stripe.webhookEndpoints.del(id)
83
- } catch (error) {
84
- if (!paymentUtils.isMissingObject(error)) {
85
- throw error
86
- }
87
- }
88
- }
89
-
90
- /** Field-encrypt the secret where the database is configured for it; store it plain otherwise. */
91
- const sealed = async (row: Partial<PaymentWebhookRecord>): Promise<Partial<PaymentWebhookRecord>> => {
92
- const resource = access.paymentWebhooks()
93
- if (typeof resource.lock !== 'function') {
94
- return row
95
- }
96
- try {
97
- return await resource.lock(row, ['secret']) as Partial<PaymentWebhookRecord>
98
- } catch {
99
- return row
100
- }
101
- }
102
-
103
- const opened = async (row: PaymentWebhookRecord): Promise<string> => {
104
- const resource = access.paymentWebhooks()
105
- if (typeof resource.unlock !== 'function') {
106
- return row.secret
107
- }
108
- try {
109
- return (await resource.unlock(row, ['secret']) as PaymentWebhookRecord).secret
110
- } catch {
111
- return row.secret
112
- }
113
- }
114
-
115
- /**
116
- * Delete the endpoints this deployment created at URLs it has left: each `payment-webhook` row of
117
- * this paygate and owner at another URL drops the endpoint it names (one already gone is fine),
118
- * then the row itself. `live` — the endpoint just put in place — is never dropped.
119
- */
120
- const pruneFormerUrls = async (stripe: Stripe, owner: string, url: string, live: string): Promise<void> => {
121
- const resource = access.paymentWebhooks()
122
- const { items } = await resource.list(
123
- { paygate: STRIPE_PAYGATE_ALIAS, service: owner, url: { $ne: url } }, { size: 0 },
124
- )
125
- for (const row of items) {
126
- if (row.externalId !== live) {
127
- await dropEndpoint(stripe, row.externalId)
128
- }
129
- await resource.delete(row.id as string)
130
- }
131
- }
53
+ const deploymentOf = (paygate: string): PaygateDeployment => ({ owner: gatewayOwnerOf(), webhookUrl: webhookUrlOf(paygate) })
132
54
 
133
55
  const ensureWebhookEndpoint = async (
134
- stripe: Stripe, opts: EnsureWebhookOptions = {},
56
+ paygate: Paygate, opts: EnsureWebhookOptions = {},
135
57
  ): Promise<PaymentWebhookRecord | null> => {
136
- const url = webhookUrlOf()
137
- if (!isDeliverableUrl(url)) {
138
- log.info('Webhook endpoint not managed: not a public https URL', { url }, { event: 'payment.webhook.unmanaged' })
58
+ if (paygate.webhook == null) {
139
59
  return null
140
60
  }
141
- const owner = gatewayOwnerOf()
142
- const apiVersion = paymentUtils.apiVersionOf(stripe)
143
- const events = [...WEBHOOK_EVENTS].sort()
144
- const hash = hashOf(url, apiVersion, events)
145
- const resource = access.paymentWebhooks()
146
- const description = `owlmeans:${owner}`
147
- const metadata = ownerMetadata(owner)
148
- const now = new Date()
149
-
150
- let stored = await resource.load({ paygate: STRIPE_PAYGATE_ALIAS, service: owner, url })
151
- if (stored != null && opts.force === true) {
152
- try {
153
- await stripe.webhookEndpoints.retrieve(stored.externalId)
154
- } catch (error) {
155
- if (!paymentUtils.isMissingObject(error)) {
156
- throw error
157
- }
158
- await resource.delete(stored.id as string)
159
- stored = null
160
- }
161
- }
162
- if (stored != null && stored.hash === hash && opts.force !== true) {
163
- return stored
164
- }
165
-
166
- let live: PaymentWebhookRecord | null = null
167
- if (stored != null && stored.apiVersion === apiVersion) {
168
- try {
169
- await stripe.webhookEndpoints.update(stored.externalId, {
170
- url, enabled_events: events as Stripe.WebhookEndpointUpdateParams.EnabledEvent[],
171
- description, metadata, disabled: false,
172
- })
173
- live = await resource.update({ ...stored, events, hash, updatedAt: now })
174
- } catch (error) {
175
- if (!paymentUtils.isMissingObject(error)) {
176
- throw error
177
- }
178
- }
179
- }
180
-
181
- if (live == null) {
182
- if (stored != null) {
183
- await dropEndpoint(stripe, stored.externalId)
184
- }
185
- for (const endpoint of await listEndpoints(stripe)) {
186
- if (endpoint.url === url) {
187
- await dropEndpoint(stripe, endpoint.id)
188
- }
189
- }
190
-
191
- const created = await stripe.webhookEndpoints.create({
192
- url, enabled_events: events as Stripe.WebhookEndpointCreateParams.EnabledEvent[],
193
- api_version: apiVersion as Stripe.WebhookEndpointCreateParams.ApiVersion, description, metadata,
194
- })
195
- if (created.secret == null || created.secret === '') {
196
- throw new WebhookSetupError('secret-missing')
197
- }
198
-
199
- const row = await sealed({
200
- paygate: STRIPE_PAYGATE_ALIAS, service: owner, url, externalId: created.id, secret: created.secret,
201
- apiVersion, events, hash, createdAt: stored?.createdAt ?? now, updatedAt: now,
202
- })
203
- try {
204
- live = stored != null
205
- ? await resource.update({ ...row, id: stored.id } as PaymentWebhookRecord)
206
- : await resource.create(row)
207
- } catch (error) {
208
- if (!paymentUtils.isDuplicateKey(error)) {
209
- throw error
210
- }
211
- // Another replica persisted its endpoint meanwhile; the one created last is the live one.
212
- const winner = await resource.load({ paygate: STRIPE_PAYGATE_ALIAS, service: owner, url })
213
- live = await resource.update({ ...row, id: winner?.id } as PaymentWebhookRecord)
214
- }
215
- }
216
-
217
- await pruneFormerUrls(stripe, owner, url, live.externalId)
218
-
219
- return live
220
- }
221
-
222
- const stripeWebhookSecrets = async (): Promise<string[]> => {
223
- const secrets: string[] = []
224
- const configured = await access.stripeConfig().then(config => config.webhook, () => undefined)
225
- if (typeof configured === 'string' && configured.trim() !== '') {
226
- secrets.push(configured.trim())
227
- }
228
- const stored = await access.paymentWebhooks().load(
229
- { paygate: STRIPE_PAYGATE_ALIAS, service: gatewayOwnerOf() },
230
- { sort: [{ field: 'updatedAt', order: 'desc' }] },
231
- )
232
- if (stored != null) {
233
- const secret = await opened(stored)
234
- if (secret !== '' && !secrets.includes(secret)) {
235
- secrets.push(secret)
236
- }
61
+ const deployment = deploymentOf(paygate.id)
62
+ if (!isDeliverableUrl(deployment.webhookUrl)) {
63
+ log.info('Webhook endpoint not managed: not a public https URL', { url: deployment.webhookUrl, paygate: paygate.id }, { event: 'payment.webhook.unmanaged' })
64
+ return null
237
65
  }
238
66
 
239
- return secrets
67
+ return await paygate.webhook.ensureEndpoint(deployment, opts)
240
68
  }
241
69
 
242
- const stripeWebhookSecret = async (): Promise<string> => {
243
- const [secret] = await stripeWebhookSecrets()
244
- if (secret == null) {
245
- throw new WebhookSetupError('secret')
70
+ const handleDelivery = async (paygate: Paygate, request: unknown): Promise<void> => {
71
+ if (paygate.webhook == null) {
72
+ throw new PaygateError('capability:webhook')
246
73
  }
247
-
248
- return secret
249
- }
250
-
251
- const handleStripeWebhook = async (stripe: Stripe, request: unknown): Promise<void> => {
252
74
  const typed = request as WebhookRequest
253
- const rawBody = typed.original?.rawBody ?? typed.rawBody
254
- const signature = typed.headers[STRIPE_SIGNATURE.toLowerCase()]
255
- if (rawBody == null || typeof signature !== 'string') throw new PaygateSignatureError()
256
-
257
- const secrets = await stripeWebhookSecrets()
258
- if (secrets.length === 0) {
259
- throw new WebhookSetupError('secret')
260
- }
261
- let event: Stripe.Event | null = null
262
- for (const secret of secrets) {
263
- try {
264
- event = await stripe.webhooks.constructEventAsync(rawBody, signature, secret)
265
- break
266
- } catch {
267
- // Try the next secret; a signature none of them verifies is refused below.
268
- }
269
- }
270
- if (event == null) {
271
- throw new PaygateSignatureError()
75
+ const events = await paygate.webhook.verify(
76
+ { rawBody: typed.original?.rawBody ?? typed.rawBody, headers: typed.headers ?? {} }, { owner: gatewayOwnerOf() },
77
+ )
78
+ for (const event of events) {
79
+ await paymentEventsOf(ctx).apply(paygate, event)
272
80
  }
273
-
274
- await createEventHandler(ctx, stripe).process(event)
275
81
  }
276
82
 
277
83
  return {
278
- webhookServiceOf, gatewayOwnerOf, webhookRouteOf, webhookUrlOf, ensureWebhookEndpoint, stripeWebhookSecrets,
279
- stripeWebhookSecret, handleStripeWebhook,
84
+ webhookServiceOf, gatewayOwnerOf, webhookRouteOf, webhookUrlOf, deploymentOf, ensureWebhookEndpoint, handleDelivery,
280
85
  }
281
86
  }
282
87
 
283
- /** The webhook endpoint of a context — one per context. */
88
+ /** The paygate webhooks of a context — one per context. */
284
89
  export const webhookOf = memoHelper.oncePer(makeWebhookHelper)
285
90
 
286
- /** @deprecated compat:factory-refactor — use `webhookOf(ctx).webhookUrlOf(…)` */
287
- export const webhookUrlOf = (ctx: ApiContext, paygate: string = STRIPE_PAYGATE_ALIAS): string =>
288
- webhookOf(ctx).webhookUrlOf(paygate)
91
+ /** @deprecated compat:factory-refactor — use `webhookOf(ctx).webhookUrlOf(paygate)` */
92
+ export const webhookUrlOf = (ctx: ApiContext, paygate: string): string => webhookOf(ctx).webhookUrlOf(paygate)
package/src/protocol.ts CHANGED
@@ -9,7 +9,7 @@ const base = protocol(route(aliases.base, '/payment-gate', backend()), contract(
9
9
  /** Embedded gateway protocol tree; the alias strings are private adapter details. */
10
10
  export const paymentGate = {
11
11
  base,
12
- /** Public: Stripe signs the raw body, so no application guard may sit in front of it. */
12
+ /** Public: the paygate signs the raw body, so no application guard may sit in front of it. */
13
13
  webhook: protocol(
14
14
  route(aliases.webhook, '/webhook/:paygate', backend({ parent: base, method: RouteMethod.POST })),
15
15
  contract.request({ params: PaygateParamsSchema }, typed<undefined>()),
package/src/service.ts CHANGED
@@ -1,7 +1,10 @@
1
- import type Stripe from 'stripe'
2
1
  import { createService } from '@owlmeans/context'
2
+ import { configHelper } from '@owlmeans/config'
3
+ import type { ConfigRecord } from '@owlmeans/context'
3
4
  import {
4
- appendPaymentService, DEFAULT_ALIAS as PAYMENT_SERVICE, ENTITLEMENT_GATE, LIMIT_GATE, PaygateError, ProductError,
5
+ appendPaymentService, CONSUMER_RIGHTS_RECORD_ID, DEFAULT_ALIAS as PAYMENT_SERVICE, DEFAULT_PRICING_POLICY,
6
+ ENTITLEMENT_GATE, LIMIT_GATE, PaygateError, PRICING_POLICY_RECORD_ID, ProductError, type ConsumerRightsPolicy,
7
+ type PricingPolicy,
5
8
  } from '@owlmeans/payment'
6
9
  import type { Context as ApiContext } from '@owlmeans/server-api'
7
10
  import {
@@ -17,15 +20,14 @@ import {
17
20
  makeFingerprintResource, makeFulfillmentResource, makeGrantResource, makePaygateCustomerResource,
18
21
  makeSubscriptionResource, makeUsageCounterResource, makeUsageResource, makeWebhookResource,
19
22
  } from './resource.js'
20
- import type {
21
- Config, Context, GatewayService, PaymentGatewayOptions, PaymentPlan, GatewayServiceOptions, StripeBootstrapOptions,
22
- } from './types.js'
23
+ import type { Config, Context, GatewayService, PaymentGatewayOptions, PaymentPlan, GatewayServiceOptions } from './types.js'
24
+ import type { PaygateFeatures } from './paygate/types.js'
23
25
  import { log } from './log.js'
24
26
  import { paymentAccessOf } from './access.js'
25
27
  import { catalogueOf } from './catalogue.js'
26
28
  import { makePlanDeclarationsModel } from './models/declarations.js'
27
29
  import { subscriptionCommitOf } from './commit.js'
28
- import { stripeBootstrapOf } from './bootstrap.js'
30
+ import { paygateBootstrapOf } from './bootstrap.js'
29
31
  import { productSyncOf } from './sync.js'
30
32
  import { estimateOf } from './plugins/estimate.js'
31
33
  import { makeEstimateCache } from './plugins/estimate/cache.js'
@@ -33,11 +35,42 @@ import { checkoutPluginsOf } from './plugins/checkout-plugins.js'
33
35
  import { makeCheckoutPluginRegistry } from './plugins/checkout-registry.js'
34
36
  import { portalOf } from './plugins/portal.js'
35
37
  import { webhookOf } from './plugins/webhook-manager.js'
36
- import { stripeSubscriptionsOf } from './plugins/subscriptions.js'
37
- import { stripeCheckoutOf } from './plugins/stripe.js'
38
+ import { paygateSubscriptionsOf } from './plugins/subscriptions.js'
39
+ import { checkoutOf } from './checkout.js'
40
+ import { appendPaymentProviders } from './paygate/providers.js'
41
+ import { paygatesOf } from './paygate/registry.js'
38
42
 
39
43
  const unmanaged = (): never => { throw new PaygateError('unmanaged') }
40
44
 
45
+ /** A singleton policy record read straight from the configuration (the boot checks run before any resource). */
46
+ const recordOf = <T>(cfg: Config, id: string): T | null => {
47
+ const record = (cfg.records ?? []).find(entry => entry.id === id)
48
+ return record != null ? configHelper.fromConfigRecord<ConfigRecord, T & { id?: string }>(record as ConfigRecord) : null
49
+ }
50
+
51
+ /**
52
+ * The policy features every registered paygate must offer: a declared pricing policy or consumer-rights
53
+ * mechanism a paygate cannot put on a checkout fails the boot.
54
+ *
55
+ * @throws PaygateError('feature:<flag>:<paygate>')
56
+ */
57
+ const assertPaygateFeatures = (ctx: ApiContext): void => {
58
+ const pricing = recordOf<PricingPolicy>(ctx.cfg, PRICING_POLICY_RECORD_ID) ?? DEFAULT_PRICING_POLICY
59
+ const rights = recordOf<ConsumerRightsPolicy>(ctx.cfg, CONSUMER_RIGHTS_RECORD_ID)
60
+ const required: Array<keyof PaygateFeatures> = [
61
+ ...(pricing.tax?.automatic === true ? ['automaticTax' as const] : []),
62
+ ...(pricing.tax?.collectTaxId === true ? ['taxIdCollection' as const] : []),
63
+ ...(pricing.currency?.adaptive === true ? ['adaptiveCurrency' as const] : []),
64
+ ...(rights?.mechanisms?.checkoutTerms === true ? ['termsConsent' as const] : []),
65
+ ]
66
+ for (const paygate of paygatesOf(ctx).all()) {
67
+ const missing = required.find(flag => paygate.features[flag] !== true)
68
+ if (missing != null) {
69
+ throw new PaygateError(`feature:${missing}:${paygate.id}`)
70
+ }
71
+ }
72
+ }
73
+
41
74
  /**
42
75
  * Refuse contradictory gateway options: `bootstrap: true` on an unmanaged gateway
43
76
  * (`PaygateError('bootstrap:unmanaged')`), an empty `owner` / `webhookService`
@@ -55,10 +88,12 @@ export const assertGatewayOptions = (opts: GatewayServiceOptions): void => {
55
88
  }
56
89
 
57
90
  /**
58
- * The gateway service. `manage`, `bootstrap`, `owner`, `webhookService` and `stripe` are
59
- * `PaymentGatewayOptions`; the options are checked here (`assertGatewayOptions`), and a managed,
60
- * bootstrapping gateway also refuses to initialize when its webhook service is not declared in
61
- * `cfg.services` (`WebhookSetupError('service:<alias>')`).
91
+ * The gateway service. `manage`, `bootstrap`, `owner` and `webhookService` are
92
+ * `PaymentGatewayOptions`; the options are checked here (`assertGatewayOptions`). At initialization a
93
+ * declared policy feature a registered paygate lacks fails the boot (`PaygateError('feature:…')`); a
94
+ * managed, bootstrapping gateway also refuses to initialize without any registered payment provider
95
+ * (`PaygateError('provider:none')`) or when its webhook service is not declared in `cfg.services`
96
+ * (`WebhookSetupError('service:<alias>')`); a managed one without a provider only warns.
62
97
  */
63
98
  export const makeGatewayService = (
64
99
  alias: string = GATEWAY_SERVICE, opts: GatewayServiceOptions = {},
@@ -66,8 +101,6 @@ export const makeGatewayService = (
66
101
  assertGatewayOptions(opts)
67
102
  const managed = opts.manage !== false
68
103
  const bootstrap = opts.bootstrap ?? managed
69
- const stripeOf = opts.stripe
70
- ?? (async (ctx: ApiContext): Promise<Stripe> => await paymentAccessOf(ctx).stripeClient())
71
104
  // One estimate cache per gateway SERVICE instance, never module-level: several service
72
105
  // instances (several tests, several deployments in one process) must never share hits.
73
106
  const estimateCache = makeEstimateCache()
@@ -82,9 +115,8 @@ export const makeGatewayService = (
82
115
  get owner(): string {
83
116
  return opts.owner ?? (service.assertCtx() as unknown as ApiContext).cfg.service
84
117
  },
85
- stripe: stripeOf,
86
118
  createLink: async (ctx, params) => managed
87
- ? await stripeCheckoutOf(ctx).createCheckoutLink(await stripeOf(ctx), params, plugins.list()) : unmanaged(),
119
+ ? await checkoutOf(ctx).createCheckoutLink(params, plugins.list()) : unmanaged(),
88
120
  use: plugin => { plugins.use(plugin) },
89
121
  checkoutPlugins: () => plugins.list(),
90
122
  amountPolicy: async (ctx, entityId, productSku, planSku) => {
@@ -96,20 +128,27 @@ export const makeGatewayService = (
96
128
  },
97
129
  planPrices: async (ctx, productSku) => await productSyncOf(ctx).syncedPlanPrices(productSku),
98
130
  portalLink: async (ctx, entityId, link) => managed
99
- ? await portalOf(ctx).createPortalLink(await stripeOf(ctx), entityId, link) : unmanaged(),
131
+ ? await portalOf(ctx).createPortalLink(entityId, link) : unmanaged(),
100
132
  grantInternalPlan: async (ctx, entityId, planSku, grant) =>
101
133
  await subscriptionCommitOf(ctx).grantInternalPlan(entityId, planSku, grant),
102
134
  revokeInternalPlan: async (ctx, entityId, planSku) =>
103
135
  await subscriptionCommitOf(ctx).revokeInternalPlan(entityId, planSku),
104
136
  resyncSubscription: async (ctx, ref) => managed
105
- ? await stripeSubscriptionsOf(ctx).resyncStripeSubscription(await stripeOf(ctx), ref) : unmanaged(),
137
+ ? await paygateSubscriptionsOf(ctx).resyncSubscription(ref) : unmanaged(),
106
138
  resyncAll: async ctx => managed
107
- ? await stripeSubscriptionsOf(ctx).resyncStripeSubscriptions(await stripeOf(ctx)) : unmanaged(),
139
+ ? await paygateSubscriptionsOf(ctx).resyncAll() : unmanaged(),
108
140
  estimatePrice: async (ctx, params) => managed
109
- ? await estimateOf(ctx).estimateStripePrice(await stripeOf(ctx), params, estimateCache) : unmanaged(),
141
+ ? await estimateOf(ctx).estimatePrice(params, estimateCache) : unmanaged(),
110
142
  }, service => async () => {
111
143
  const ctx = service.assertCtx() as unknown as ApiContext
112
144
  makePlanDeclarationsModel(ctx.cfg).assertPlans()
145
+ assertPaygateFeatures(ctx)
146
+ if (managed && paygatesOf(ctx).all().length === 0) {
147
+ if (bootstrap) {
148
+ throw new PaygateError('provider:none')
149
+ }
150
+ log.warn('Payment gateway is managed but no payment provider is registered: checkout, the portal and the webhook refuse')
151
+ }
113
152
  if (bootstrap) {
114
153
  // Every boot bootstrap forms the webhook URL on this alias: an undeclared one fails the boot.
115
154
  webhookOf(ctx).webhookRouteOf(opts.webhookService ?? ctx.cfg.service)
@@ -120,8 +159,8 @@ export const makeGatewayService = (
120
159
  paymentAccessOf(ctx).consumerRightsOf()
121
160
  if (bootstrap) {
122
161
  void ctx.waitForInitialized().then(async () => {
123
- await stripeBootstrapOf(ctx).bootstrapStripe(await stripeOf(ctx))
124
- }).catch(error => { log.error('Stripe bootstrap failed', error) })
162
+ await paygateBootstrapOf(ctx).bootstrap()
163
+ }).catch(error => { log.error('Paygate bootstrap failed', error) })
125
164
  }
126
165
  })
127
166
 
@@ -134,8 +173,10 @@ export const makeGatewayService = (
134
173
  * entitlement service and the consumer-rights records and service — each only when not registered yet.
135
174
  *
136
175
  * `manage: false` registers the same surface for a process that reads entitlements but never talks
137
- * to Stripe. Several managed processes of one deployment share the Stripe rows through one `owner`
138
- * and one `webhookService`; exactly one of them keeps `bootstrap` (the one receiving the webhook).
176
+ * to a paygate. Several managed processes of one deployment share the paygate rows through one
177
+ * `owner` and one `webhookService`; exactly one of them keeps `bootstrap` (the one receiving the
178
+ * webhook). The paygates themselves come from the payment providers registered with
179
+ * `ensurePaymentProviders(ctx).register(…)` (a provider package's `append…` helper), before or after.
139
180
  */
140
181
  export const appendPaymentGatewayService = <C extends Config, T extends Context<C>>(
141
182
  ctx: T, opts?: PaymentGatewayOptions,
@@ -156,11 +197,11 @@ export const appendPaymentGatewayService = <C extends Config, T extends Context<
156
197
  }
157
198
  }
158
199
  if (!ctx.hasService(PAYMENT_SERVICE)) appendPaymentService(ctx as never)
200
+ appendPaymentProviders(ctx)
159
201
  appendCompletionObserver(ctx)
160
202
  if (!ctx.hasService(GATEWAY_SERVICE)) {
161
203
  ctx.registerService(makeGatewayService(GATEWAY_SERVICE, {
162
204
  manage: opts?.manage, bootstrap: opts?.bootstrap, owner: opts?.owner, webhookService: opts?.webhookService,
163
- stripe: opts?.stripe,
164
205
  }))
165
206
  }
166
207
  if (!ctx.hasService(ENTITLEMENT_GATE)) ctx.registerService(makeCapabilityGate())
@@ -173,8 +214,3 @@ export const appendPaymentGatewayService = <C extends Config, T extends Context<
173
214
 
174
215
  return ctx
175
216
  }
176
-
177
- /** @deprecated compat:factory-refactor — use `stripeBootstrapOf(ctx).bootstrapStripe(…)` */
178
- export const bootstrapStripe = async (
179
- ctx: ApiContext, stripe: Stripe, opts: StripeBootstrapOptions = {},
180
- ): Promise<void> => { await stripeBootstrapOf(ctx).bootstrapStripe(stripe, opts) }
package/src/sync/types.ts CHANGED
@@ -1,25 +1,29 @@
1
- import type Stripe from 'stripe'
2
1
  import type { PlanPriceView } from '@owlmeans/payment'
2
+ import type { Paygate } from '../paygate/types.js'
3
3
 
4
- /** The catalogue of a context as Stripe products and prices. */
4
+ /** The catalogue of a context as each paygate's products and reusable prices. */
5
5
  export interface ProductSyncHelper {
6
6
  /**
7
- * Synchronize every product sold through Stripe, and its Stripe-sold plans, to Stripe products and
8
- * prices. A product whose declaration fingerprint is unchanged makes no paygate call. Free plans
9
- * and plans sold through no Stripe gateway are never synchronized.
7
+ * Synchronize every product with a plan sold through the paygate, and those plans, to the
8
+ * paygate's catalogue (`paygate.catalogue.syncProduct`). A product whose declaration fingerprint is
9
+ * unchanged makes no paygate call; free plans and plans sold through other paygates are never
10
+ * synchronized; a paygate without `catalogue` is skipped. A recurring or quantity plan whose
11
+ * catalogue currency differs from the paygate's settlement currency is converted at its FX reference
12
+ * rate (rounded up).
10
13
  *
11
- * The declared `PricingPolicy.tax.behavior` (absent by default, so a price's `tax_behavior` stays
12
- * whatever it already was) is applied to a matching price only while it is `unspecified` — Stripe
13
- * forbids changing a price once set to `exclusive` or `inclusive` — and to a fresh one on creation.
14
- * A price carrying the OPPOSITE behavior is deactivated and replaced, same as any other mismatch.
14
+ * The declared `PricingPolicy.tax.behavior` (absent by default) is applied by the paygate to a
15
+ * matching price it can still change, and to a fresh one on creation; a price carrying the
16
+ * OPPOSITE behavior is replaced, same as any other mismatch. Each sync stores the product's
17
+ * `prices[]` on its fingerprint row — what `planPrices`, checkout currency forcing and the estimate
18
+ * read. The fingerprint row is keyed by the product sku: one paygate syncs a product's catalogue.
15
19
  */
16
- syncStripeProducts: (stripe: Stripe) => Promise<void>
20
+ syncProducts: (paygate: Paygate) => Promise<void>
17
21
  /**
18
22
  * The prices a product's plans are charged at, per currency, as the last sync stored them — no
19
- * paygate call, so it works in an unmanaged process. One entry for each Price's default currency
20
- * (`default: true`) and one per currency option.
23
+ * paygate call, so it works in an unmanaged process. One entry for each price's default currency
24
+ * (`default: true`) and one per further currency.
21
25
  */
22
26
  syncedPlanPrices: (productSku: string) => Promise<PlanPriceView[]>
23
- /** `syncStripeProducts` with this context's own Stripe client (the gateway's, else the configured secret). */
27
+ /** `syncProducts` for every registered paygate. */
24
28
  syncPaymentProducts: () => Promise<void>
25
29
  }