@owlmeans/server-payment 0.1.18-rc.9 → 0.1.18

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 (537) hide show
  1. package/README.md +157 -26
  2. package/agent-meta/manifest.json +30 -4
  3. package/agent-meta/skills/server-payment/SKILL.md +613 -54
  4. package/agent-meta/skills/server-payment/parts/reference.md +174 -0
  5. package/build/access/types.d.ts +46 -0
  6. package/build/access/types.d.ts.map +1 -0
  7. package/build/access/types.js +2 -0
  8. package/build/access/types.js.map +1 -0
  9. package/build/access.d.ts +6 -0
  10. package/build/access.d.ts.map +1 -0
  11. package/build/access.js +45 -0
  12. package/build/access.js.map +1 -0
  13. package/build/actions/index.d.ts +1 -0
  14. package/build/actions/index.d.ts.map +1 -1
  15. package/build/actions/index.js +1 -0
  16. package/build/actions/index.js.map +1 -1
  17. package/build/actions/resync-subscriptions.d.ts +3 -0
  18. package/build/actions/resync-subscriptions.d.ts.map +1 -0
  19. package/build/actions/resync-subscriptions.js +7 -0
  20. package/build/actions/resync-subscriptions.js.map +1 -0
  21. package/build/actions/resync.d.ts +6 -1
  22. package/build/actions/resync.d.ts.map +1 -1
  23. package/build/actions/resync.js +15 -5
  24. package/build/actions/resync.js.map +1 -1
  25. package/build/actions/webhook.d.ts +2 -1
  26. package/build/actions/webhook.d.ts.map +1 -1
  27. package/build/actions/webhook.js +10 -4
  28. package/build/actions/webhook.js.map +1 -1
  29. package/build/bootstrap/types.d.ts +16 -0
  30. package/build/bootstrap/types.d.ts.map +1 -0
  31. package/build/bootstrap/types.js +2 -0
  32. package/build/bootstrap/types.js.map +1 -0
  33. package/build/bootstrap.d.ts +6 -0
  34. package/build/bootstrap.d.ts.map +1 -0
  35. package/build/bootstrap.js +26 -0
  36. package/build/bootstrap.js.map +1 -0
  37. package/build/catalogue/types.d.ts +38 -0
  38. package/build/catalogue/types.d.ts.map +1 -0
  39. package/build/catalogue/types.js +2 -0
  40. package/build/catalogue/types.js.map +1 -0
  41. package/build/catalogue.d.ts +6 -0
  42. package/build/catalogue.d.ts.map +1 -0
  43. package/build/catalogue.js +110 -0
  44. package/build/catalogue.js.map +1 -0
  45. package/build/commit/types.d.ts +22 -0
  46. package/build/commit/types.d.ts.map +1 -0
  47. package/build/commit/types.js +2 -0
  48. package/build/commit/types.js.map +1 -0
  49. package/build/commit.d.ts +6 -0
  50. package/build/commit.d.ts.map +1 -0
  51. package/build/commit.js +125 -0
  52. package/build/commit.js.map +1 -0
  53. package/build/config.d.ts +44 -5
  54. package/build/config.d.ts.map +1 -1
  55. package/build/config.js +216 -10
  56. package/build/config.js.map +1 -1
  57. package/build/consts.d.ts +74 -16
  58. package/build/consts.d.ts.map +1 -1
  59. package/build/consts.js +86 -23
  60. package/build/consts.js.map +1 -1
  61. package/build/consts.local.d.ts +94 -0
  62. package/build/consts.local.d.ts.map +1 -0
  63. package/build/consts.local.js +44 -0
  64. package/build/consts.local.js.map +1 -0
  65. package/build/consumer/cancellation/types.d.ts +11 -0
  66. package/build/consumer/cancellation/types.d.ts.map +1 -0
  67. package/build/consumer/cancellation/types.js +2 -0
  68. package/build/consumer/cancellation/types.js.map +1 -0
  69. package/build/consumer/cancellation.d.ts +6 -0
  70. package/build/consumer/cancellation.d.ts.map +1 -0
  71. package/build/consumer/cancellation.js +33 -0
  72. package/build/consumer/cancellation.js.map +1 -0
  73. package/build/consumer/capture/types.d.ts +50 -0
  74. package/build/consumer/capture/types.d.ts.map +1 -0
  75. package/build/consumer/capture/types.js +2 -0
  76. package/build/consumer/capture/types.js.map +1 -0
  77. package/build/consumer/capture.d.ts +6 -0
  78. package/build/consumer/capture.d.ts.map +1 -0
  79. package/build/consumer/capture.js +284 -0
  80. package/build/consumer/capture.js.map +1 -0
  81. package/build/consumer/consts.local.d.ts +10 -0
  82. package/build/consumer/consts.local.d.ts.map +1 -0
  83. package/build/consumer/consts.local.js +11 -0
  84. package/build/consumer/consts.local.js.map +1 -0
  85. package/build/consumer/format/types.d.ts +30 -0
  86. package/build/consumer/format/types.d.ts.map +1 -0
  87. package/build/consumer/format/types.js +2 -0
  88. package/build/consumer/format/types.js.map +1 -0
  89. package/build/consumer/format.d.ts +4 -0
  90. package/build/consumer/format.d.ts.map +1 -0
  91. package/build/consumer/format.js +73 -0
  92. package/build/consumer/format.js.map +1 -0
  93. package/build/consumer/handlers.d.ts +21 -0
  94. package/build/consumer/handlers.d.ts.map +1 -0
  95. package/build/consumer/handlers.js +174 -0
  96. package/build/consumer/handlers.js.map +1 -0
  97. package/build/consumer/index.d.ts +10 -0
  98. package/build/consumer/index.d.ts.map +1 -0
  99. package/build/consumer/index.js +6 -0
  100. package/build/consumer/index.js.map +1 -0
  101. package/build/consumer/mail/types.d.ts +29 -0
  102. package/build/consumer/mail/types.d.ts.map +1 -0
  103. package/build/consumer/mail/types.js +2 -0
  104. package/build/consumer/mail/types.js.map +1 -0
  105. package/build/consumer/mail.d.ts +6 -0
  106. package/build/consumer/mail.d.ts.map +1 -0
  107. package/build/consumer/mail.js +313 -0
  108. package/build/consumer/mail.js.map +1 -0
  109. package/build/consumer/observers/types.d.ts +15 -0
  110. package/build/consumer/observers/types.d.ts.map +1 -0
  111. package/build/consumer/observers/types.js +2 -0
  112. package/build/consumer/observers/types.js.map +1 -0
  113. package/build/consumer/observers.d.ts +6 -0
  114. package/build/consumer/observers.d.ts.map +1 -0
  115. package/build/consumer/observers.js +74 -0
  116. package/build/consumer/observers.js.map +1 -0
  117. package/build/consumer/origin/types.d.ts +17 -0
  118. package/build/consumer/origin/types.d.ts.map +1 -0
  119. package/build/consumer/origin/types.js +2 -0
  120. package/build/consumer/origin/types.js.map +1 -0
  121. package/build/consumer/origin.d.ts +8 -0
  122. package/build/consumer/origin.d.ts.map +1 -0
  123. package/build/consumer/origin.js +43 -0
  124. package/build/consumer/origin.js.map +1 -0
  125. package/build/consumer/reconcile/types.d.ts +13 -0
  126. package/build/consumer/reconcile/types.d.ts.map +1 -0
  127. package/build/consumer/reconcile/types.js +2 -0
  128. package/build/consumer/reconcile/types.js.map +1 -0
  129. package/build/consumer/reconcile.d.ts +5 -0
  130. package/build/consumer/reconcile.d.ts.map +1 -0
  131. package/build/consumer/reconcile.js +320 -0
  132. package/build/consumer/reconcile.js.map +1 -0
  133. package/build/consumer/records/types.d.ts +66 -0
  134. package/build/consumer/records/types.d.ts.map +1 -0
  135. package/build/consumer/records/types.js +2 -0
  136. package/build/consumer/records/types.js.map +1 -0
  137. package/build/consumer/records.d.ts +6 -0
  138. package/build/consumer/records.d.ts.map +1 -0
  139. package/build/consumer/records.js +243 -0
  140. package/build/consumer/records.js.map +1 -0
  141. package/build/consumer/service.d.ts +28 -0
  142. package/build/consumer/service.d.ts.map +1 -0
  143. package/build/consumer/service.js +706 -0
  144. package/build/consumer/service.js.map +1 -0
  145. package/build/consumer/types.d.ts +84 -0
  146. package/build/consumer/types.d.ts.map +1 -0
  147. package/build/consumer/types.js +2 -0
  148. package/build/consumer/types.js.map +1 -0
  149. package/build/consumer/types.local.d.ts +26 -0
  150. package/build/consumer/types.local.d.ts.map +1 -0
  151. package/build/consumer/types.local.js +2 -0
  152. package/build/consumer/types.local.js.map +1 -0
  153. package/build/consumer/withdrawal/types.d.ts +36 -0
  154. package/build/consumer/withdrawal/types.d.ts.map +1 -0
  155. package/build/consumer/withdrawal/types.js +2 -0
  156. package/build/consumer/withdrawal/types.js.map +1 -0
  157. package/build/consumer/withdrawal.d.ts +6 -0
  158. package/build/consumer/withdrawal.d.ts.map +1 -0
  159. package/build/consumer/withdrawal.js +237 -0
  160. package/build/consumer/withdrawal.js.map +1 -0
  161. package/build/entitlement.d.ts +4 -0
  162. package/build/entitlement.d.ts.map +1 -0
  163. package/build/entitlement.js +72 -0
  164. package/build/entitlement.js.map +1 -0
  165. package/build/entrypoints.d.ts +19 -2
  166. package/build/entrypoints.d.ts.map +1 -1
  167. package/build/entrypoints.js +16 -4
  168. package/build/entrypoints.js.map +1 -1
  169. package/build/gate/request.d.ts +4 -0
  170. package/build/gate/request.d.ts.map +1 -0
  171. package/build/gate/request.js +17 -0
  172. package/build/gate/request.js.map +1 -0
  173. package/build/gate/types.d.ts +15 -0
  174. package/build/gate/types.d.ts.map +1 -0
  175. package/build/gate/types.js +2 -0
  176. package/build/gate/types.js.map +1 -0
  177. package/build/gate.d.ts +13 -9
  178. package/build/gate.d.ts.map +1 -1
  179. package/build/gate.js +36 -21
  180. package/build/gate.js.map +1 -1
  181. package/build/index.d.ts +50 -3
  182. package/build/index.d.ts.map +1 -1
  183. package/build/index.js +29 -3
  184. package/build/index.js.map +1 -1
  185. package/build/limit.d.ts +11 -0
  186. package/build/limit.d.ts.map +1 -0
  187. package/build/limit.js +48 -0
  188. package/build/limit.js.map +1 -0
  189. package/build/log.d.ts +3 -0
  190. package/build/log.d.ts.map +1 -0
  191. package/build/log.js +4 -0
  192. package/build/log.js.map +1 -0
  193. package/build/models/declarations/types.d.ts +22 -0
  194. package/build/models/declarations/types.d.ts.map +1 -0
  195. package/build/models/declarations/types.js +2 -0
  196. package/build/models/declarations/types.js.map +1 -0
  197. package/build/models/declarations.d.ts +4 -0
  198. package/build/models/declarations.d.ts.map +1 -0
  199. package/build/models/declarations.js +26 -0
  200. package/build/models/declarations.js.map +1 -0
  201. package/build/models/purchase/types.d.ts +13 -0
  202. package/build/models/purchase/types.d.ts.map +1 -0
  203. package/build/models/purchase/types.js +2 -0
  204. package/build/models/purchase/types.js.map +1 -0
  205. package/build/models/purchase.d.ts +4 -0
  206. package/build/models/purchase.d.ts.map +1 -0
  207. package/build/models/purchase.js +37 -0
  208. package/build/models/purchase.js.map +1 -0
  209. package/build/observer.d.ts +9 -0
  210. package/build/observer.d.ts.map +1 -1
  211. package/build/observer.js +38 -12
  212. package/build/observer.js.map +1 -1
  213. package/build/plan/types.d.ts +21 -0
  214. package/build/plan/types.d.ts.map +1 -0
  215. package/build/plan/types.js +2 -0
  216. package/build/plan/types.js.map +1 -0
  217. package/build/plan.d.ts +7 -0
  218. package/build/plan.d.ts.map +1 -0
  219. package/build/plan.js +29 -0
  220. package/build/plan.js.map +1 -0
  221. package/build/plugins/checkout-plugins/types.d.ts +25 -0
  222. package/build/plugins/checkout-plugins/types.d.ts.map +1 -0
  223. package/build/plugins/checkout-plugins/types.js +2 -0
  224. package/build/plugins/checkout-plugins/types.js.map +1 -0
  225. package/build/plugins/checkout-plugins.d.ts +12 -0
  226. package/build/plugins/checkout-plugins.d.ts.map +1 -0
  227. package/build/plugins/checkout-plugins.js +72 -0
  228. package/build/plugins/checkout-plugins.js.map +1 -0
  229. package/build/plugins/checkout-policy/types.d.ts +18 -0
  230. package/build/plugins/checkout-policy/types.d.ts.map +1 -0
  231. package/build/plugins/checkout-policy/types.js +2 -0
  232. package/build/plugins/checkout-policy/types.js.map +1 -0
  233. package/build/plugins/checkout-policy.d.ts +4 -0
  234. package/build/plugins/checkout-policy.d.ts.map +1 -0
  235. package/build/plugins/checkout-policy.js +26 -0
  236. package/build/plugins/checkout-policy.js.map +1 -0
  237. package/build/plugins/checkout-registry/types.d.ts +7 -0
  238. package/build/plugins/checkout-registry/types.d.ts.map +1 -0
  239. package/build/plugins/checkout-registry/types.js +2 -0
  240. package/build/plugins/checkout-registry/types.js.map +1 -0
  241. package/build/plugins/checkout-registry.d.ts +8 -0
  242. package/build/plugins/checkout-registry.d.ts.map +1 -0
  243. package/build/plugins/checkout-registry.js +21 -0
  244. package/build/plugins/checkout-registry.js.map +1 -0
  245. package/build/plugins/consts.local.d.ts +13 -0
  246. package/build/plugins/consts.local.d.ts.map +1 -0
  247. package/build/plugins/consts.local.js +22 -0
  248. package/build/plugins/consts.local.js.map +1 -0
  249. package/build/plugins/customer-lock/types.d.ts +6 -0
  250. package/build/plugins/customer-lock/types.d.ts.map +1 -0
  251. package/build/plugins/customer-lock/types.js +2 -0
  252. package/build/plugins/customer-lock/types.js.map +1 -0
  253. package/build/plugins/customer-lock.d.ts +5 -0
  254. package/build/plugins/customer-lock.d.ts.map +1 -0
  255. package/build/plugins/customer-lock.js +22 -0
  256. package/build/plugins/customer-lock.js.map +1 -0
  257. package/build/plugins/estimate/cache.d.ts +4 -0
  258. package/build/plugins/estimate/cache.d.ts.map +1 -0
  259. package/build/plugins/estimate/cache.js +7 -0
  260. package/build/plugins/estimate/cache.js.map +1 -0
  261. package/build/plugins/estimate/types.d.ts +27 -0
  262. package/build/plugins/estimate/types.d.ts.map +1 -0
  263. package/build/plugins/estimate/types.js +2 -0
  264. package/build/plugins/estimate/types.js.map +1 -0
  265. package/build/plugins/estimate.d.ts +6 -0
  266. package/build/plugins/estimate.d.ts.map +1 -0
  267. package/build/plugins/estimate.js +271 -0
  268. package/build/plugins/estimate.js.map +1 -0
  269. package/build/plugins/events/types.d.ts +12 -0
  270. package/build/plugins/events/types.d.ts.map +1 -0
  271. package/build/plugins/events/types.js +2 -0
  272. package/build/plugins/events/types.js.map +1 -0
  273. package/build/plugins/events.d.ts +6 -13
  274. package/build/plugins/events.d.ts.map +1 -1
  275. package/build/plugins/events.js +441 -144
  276. package/build/plugins/events.js.map +1 -1
  277. package/build/plugins/fx/types.d.ts +33 -0
  278. package/build/plugins/fx/types.d.ts.map +1 -0
  279. package/build/plugins/fx/types.js +2 -0
  280. package/build/plugins/fx/types.js.map +1 -0
  281. package/build/plugins/fx.d.ts +6 -0
  282. package/build/plugins/fx.d.ts.map +1 -0
  283. package/build/plugins/fx.js +83 -0
  284. package/build/plugins/fx.js.map +1 -0
  285. package/build/plugins/portal/types.d.ts +44 -0
  286. package/build/plugins/portal/types.d.ts.map +1 -0
  287. package/build/plugins/portal/types.js +2 -0
  288. package/build/plugins/portal/types.js.map +1 -0
  289. package/build/plugins/portal.d.ts +6 -0
  290. package/build/plugins/portal.d.ts.map +1 -0
  291. package/build/plugins/portal.js +255 -0
  292. package/build/plugins/portal.js.map +1 -0
  293. package/build/plugins/refunds/types.d.ts +35 -0
  294. package/build/plugins/refunds/types.d.ts.map +1 -0
  295. package/build/plugins/refunds/types.js +2 -0
  296. package/build/plugins/refunds/types.js.map +1 -0
  297. package/build/plugins/refunds.d.ts +6 -0
  298. package/build/plugins/refunds.d.ts.map +1 -0
  299. package/build/plugins/refunds.js +81 -0
  300. package/build/plugins/refunds.js.map +1 -0
  301. package/build/plugins/session/types.d.ts +32 -0
  302. package/build/plugins/session/types.d.ts.map +1 -0
  303. package/build/plugins/session/types.js +2 -0
  304. package/build/plugins/session/types.js.map +1 -0
  305. package/build/plugins/session.d.ts +4 -0
  306. package/build/plugins/session.d.ts.map +1 -0
  307. package/build/plugins/session.js +58 -0
  308. package/build/plugins/session.js.map +1 -0
  309. package/build/plugins/status.d.ts +8 -0
  310. package/build/plugins/status.d.ts.map +1 -0
  311. package/build/plugins/status.js +21 -0
  312. package/build/plugins/status.js.map +1 -0
  313. package/build/plugins/stripe/types.d.ts +20 -0
  314. package/build/plugins/stripe/types.d.ts.map +1 -0
  315. package/build/plugins/stripe/types.js +2 -0
  316. package/build/plugins/stripe/types.js.map +1 -0
  317. package/build/plugins/stripe.d.ts +5 -13
  318. package/build/plugins/stripe.d.ts.map +1 -1
  319. package/build/plugins/stripe.js +481 -129
  320. package/build/plugins/stripe.js.map +1 -1
  321. package/build/plugins/subscriptions/types.d.ts +41 -0
  322. package/build/plugins/subscriptions/types.d.ts.map +1 -0
  323. package/build/plugins/subscriptions/types.js +2 -0
  324. package/build/plugins/subscriptions/types.js.map +1 -0
  325. package/build/plugins/subscriptions.d.ts +6 -0
  326. package/build/plugins/subscriptions.d.ts.map +1 -0
  327. package/build/plugins/subscriptions.js +169 -0
  328. package/build/plugins/subscriptions.js.map +1 -0
  329. package/build/plugins/types.d.ts +7 -0
  330. package/build/plugins/types.d.ts.map +1 -0
  331. package/build/plugins/types.js +2 -0
  332. package/build/plugins/types.js.map +1 -0
  333. package/build/plugins/types.local.d.ts +75 -0
  334. package/build/plugins/types.local.d.ts.map +1 -0
  335. package/build/plugins/types.local.js +2 -0
  336. package/build/plugins/types.local.js.map +1 -0
  337. package/build/plugins/webhook-manager/types.d.ts +62 -0
  338. package/build/plugins/webhook-manager/types.d.ts.map +1 -0
  339. package/build/plugins/webhook-manager/types.js +2 -0
  340. package/build/plugins/webhook-manager/types.js.map +1 -0
  341. package/build/plugins/webhook-manager.d.ts +8 -0
  342. package/build/plugins/webhook-manager.d.ts.map +1 -0
  343. package/build/plugins/webhook-manager.js +245 -0
  344. package/build/plugins/webhook-manager.js.map +1 -0
  345. package/build/protocol.d.ts +13 -0
  346. package/build/protocol.d.ts.map +1 -0
  347. package/build/protocol.js +17 -0
  348. package/build/protocol.js.map +1 -0
  349. package/build/reconcile/types.d.ts +17 -0
  350. package/build/reconcile/types.d.ts.map +1 -0
  351. package/build/reconcile/types.js +2 -0
  352. package/build/reconcile/types.js.map +1 -0
  353. package/build/reconcile.d.ts +12 -0
  354. package/build/reconcile.d.ts.map +1 -0
  355. package/build/reconcile.js +91 -0
  356. package/build/reconcile.js.map +1 -0
  357. package/build/resource.d.ts +12 -1
  358. package/build/resource.d.ts.map +1 -1
  359. package/build/resource.js +97 -6
  360. package/build/resource.js.map +1 -1
  361. package/build/schemas.d.ts +19 -0
  362. package/build/schemas.d.ts.map +1 -0
  363. package/build/schemas.js +244 -0
  364. package/build/schemas.js.map +1 -0
  365. package/build/service.d.ts +28 -3
  366. package/build/service.d.ts.map +1 -1
  367. package/build/service.js +140 -19
  368. package/build/service.js.map +1 -1
  369. package/build/subscription/types.d.ts +21 -0
  370. package/build/subscription/types.d.ts.map +1 -0
  371. package/build/subscription/types.js +2 -0
  372. package/build/subscription/types.js.map +1 -0
  373. package/build/subscription.d.ts +4 -0
  374. package/build/subscription.d.ts.map +1 -0
  375. package/build/subscription.js +84 -0
  376. package/build/subscription.js.map +1 -0
  377. package/build/sync/types.d.ts +25 -0
  378. package/build/sync/types.d.ts.map +1 -0
  379. package/build/sync/types.js +2 -0
  380. package/build/sync/types.js.map +1 -0
  381. package/build/sync.d.ts +4 -3
  382. package/build/sync.d.ts.map +1 -1
  383. package/build/sync.js +231 -79
  384. package/build/sync.js.map +1 -1
  385. package/build/types.d.ts +1258 -36
  386. package/build/types.d.ts.map +1 -1
  387. package/build/types.local.d.ts +22 -0
  388. package/build/types.local.d.ts.map +1 -0
  389. package/build/types.local.js +2 -0
  390. package/build/types.local.js.map +1 -0
  391. package/build/usage/types.d.ts +56 -0
  392. package/build/usage/types.d.ts.map +1 -0
  393. package/build/usage/types.js +2 -0
  394. package/build/usage/types.js.map +1 -0
  395. package/build/usage.d.ts +6 -0
  396. package/build/usage.d.ts.map +1 -0
  397. package/build/usage.js +365 -0
  398. package/build/usage.js.map +1 -0
  399. package/build/utils/types.d.ts +31 -0
  400. package/build/utils/types.d.ts.map +1 -0
  401. package/build/utils/types.js +2 -0
  402. package/build/utils/types.js.map +1 -0
  403. package/build/utils.d.ts +21 -7
  404. package/build/utils.d.ts.map +1 -1
  405. package/build/utils.js +56 -17
  406. package/build/utils.js.map +1 -1
  407. package/package.json +22 -17
  408. package/src/access/types.ts +52 -0
  409. package/src/access.ts +86 -0
  410. package/src/actions/index.ts +1 -0
  411. package/src/actions/resync-subscriptions.ts +10 -0
  412. package/src/actions/resync.ts +14 -5
  413. package/src/actions/webhook.ts +9 -4
  414. package/src/bootstrap/types.ts +16 -0
  415. package/src/bootstrap.ts +31 -0
  416. package/src/catalogue/types.ts +32 -0
  417. package/src/catalogue.ts +135 -0
  418. package/src/commit/types.ts +27 -0
  419. package/src/commit.ts +152 -0
  420. package/src/config.ts +234 -14
  421. package/src/consts.local.ts +62 -0
  422. package/src/consts.ts +100 -36
  423. package/src/consumer/cancellation/types.ts +13 -0
  424. package/src/consumer/cancellation.ts +43 -0
  425. package/src/consumer/capture/types.ts +53 -0
  426. package/src/consumer/capture.ts +321 -0
  427. package/src/consumer/consts.local.ts +18 -0
  428. package/src/consumer/format/types.ts +29 -0
  429. package/src/consumer/format.ts +85 -0
  430. package/src/consumer/handlers.ts +204 -0
  431. package/src/consumer/index.ts +9 -0
  432. package/src/consumer/mail/types.ts +31 -0
  433. package/src/consumer/mail.ts +353 -0
  434. package/src/consumer/observers/types.ts +22 -0
  435. package/src/consumer/observers.ts +97 -0
  436. package/src/consumer/origin/types.ts +17 -0
  437. package/src/consumer/origin.ts +61 -0
  438. package/src/consumer/reconcile/types.ts +13 -0
  439. package/src/consumer/reconcile.ts +330 -0
  440. package/src/consumer/records/types.ts +64 -0
  441. package/src/consumer/records.ts +288 -0
  442. package/src/consumer/service.ts +768 -0
  443. package/src/consumer/types.local.ts +22 -0
  444. package/src/consumer/types.ts +96 -0
  445. package/src/consumer/withdrawal/types.ts +37 -0
  446. package/src/consumer/withdrawal.ts +268 -0
  447. package/src/entitlement.ts +85 -0
  448. package/src/entrypoints.ts +17 -4
  449. package/src/gate/request.ts +24 -0
  450. package/src/gate/types.ts +13 -0
  451. package/src/gate.ts +47 -30
  452. package/src/index.ts +55 -3
  453. package/src/limit.ts +54 -0
  454. package/src/log.ts +4 -0
  455. package/src/models/declarations/types.ts +22 -0
  456. package/src/models/declarations.ts +30 -0
  457. package/src/models/purchase/types.ts +13 -0
  458. package/src/models/purchase.ts +43 -0
  459. package/src/observer.ts +44 -11
  460. package/src/plan/types.ts +21 -0
  461. package/src/plan.ts +46 -0
  462. package/src/plugins/checkout-plugins/types.ts +25 -0
  463. package/src/plugins/checkout-plugins.ts +90 -0
  464. package/src/plugins/checkout-policy/types.ts +18 -0
  465. package/src/plugins/checkout-policy.ts +34 -0
  466. package/src/plugins/checkout-registry/types.ts +7 -0
  467. package/src/plugins/checkout-registry.ts +23 -0
  468. package/src/plugins/consts.local.ts +30 -0
  469. package/src/plugins/customer-lock/types.ts +5 -0
  470. package/src/plugins/customer-lock.ts +25 -0
  471. package/src/plugins/estimate/cache.ts +12 -0
  472. package/src/plugins/estimate/types.ts +28 -0
  473. package/src/plugins/estimate.ts +305 -0
  474. package/src/plugins/events/types.ts +11 -0
  475. package/src/plugins/events.ts +466 -132
  476. package/src/plugins/fx/types.ts +40 -0
  477. package/src/plugins/fx.ts +101 -0
  478. package/src/plugins/portal/types.ts +45 -0
  479. package/src/plugins/portal.ts +284 -0
  480. package/src/plugins/refunds/types.ts +31 -0
  481. package/src/plugins/refunds.ts +95 -0
  482. package/src/plugins/session/types.ts +28 -0
  483. package/src/plugins/session.ts +73 -0
  484. package/src/plugins/status.ts +22 -0
  485. package/src/plugins/stripe/types.ts +20 -0
  486. package/src/plugins/stripe.ts +523 -135
  487. package/src/plugins/subscriptions/types.ts +39 -0
  488. package/src/plugins/subscriptions.ts +195 -0
  489. package/src/plugins/types.local.ts +61 -0
  490. package/src/plugins/types.ts +7 -0
  491. package/src/plugins/webhook-manager/types.ts +63 -0
  492. package/src/plugins/webhook-manager.ts +288 -0
  493. package/src/protocol.ts +29 -0
  494. package/src/reconcile/types.ts +17 -0
  495. package/src/reconcile.ts +110 -0
  496. package/src/resource.ts +158 -11
  497. package/src/schemas.ts +271 -0
  498. package/src/service.ts +161 -19
  499. package/src/subscription/types.ts +23 -0
  500. package/src/subscription.ts +104 -0
  501. package/src/sync/types.ts +25 -0
  502. package/src/sync.ts +255 -72
  503. package/src/types.local.ts +18 -0
  504. package/src/types.ts +1365 -32
  505. package/src/usage/types.ts +51 -0
  506. package/src/usage.ts +432 -0
  507. package/src/utils/types.ts +30 -0
  508. package/src/utils.ts +94 -29
  509. package/tests/checkout-consumer.spec.ts +366 -0
  510. package/tests/checkout-locks.spec.ts +161 -0
  511. package/tests/checkout-plugins.spec.ts +164 -0
  512. package/tests/checkout.spec.ts +209 -93
  513. package/tests/consumer-events.spec.ts +215 -0
  514. package/tests/consumer-fixtures.ts +134 -0
  515. package/tests/consumer-ops.spec.ts +350 -0
  516. package/tests/consumer-rights.integration.spec.ts +147 -0
  517. package/tests/consumer-rights.spec.ts +572 -0
  518. package/tests/context.ts +110 -0
  519. package/tests/entitlement.spec.ts +139 -0
  520. package/tests/estimate.spec.ts +350 -0
  521. package/tests/events.spec.ts +357 -0
  522. package/tests/fake-stripe.ts +981 -0
  523. package/tests/gate-handlers.spec.ts +120 -0
  524. package/tests/gate.spec.ts +63 -72
  525. package/tests/gateway-options.spec.ts +180 -0
  526. package/tests/limit-gate.spec.ts +66 -0
  527. package/tests/portal.spec.ts +202 -0
  528. package/tests/protocol.spec.ts +17 -3
  529. package/tests/sync.spec.ts +114 -0
  530. package/tests/usage.integration.spec.ts +133 -0
  531. package/tests/usage.spec.ts +169 -0
  532. package/tests/webhook-manager.spec.ts +149 -0
  533. package/build/model.d.ts +0 -6
  534. package/build/model.d.ts.map +0 -1
  535. package/build/model.js +0 -33
  536. package/build/model.js.map +0 -1
  537. package/src/model.ts +0 -37
@@ -0,0 +1,39 @@
1
+ import type Stripe from 'stripe'
2
+ import type { SubscriptionStatus } from '@owlmeans/payment'
3
+ import type { CommitResult, SubscriptionRef } from '../../types.js'
4
+
5
+ export interface ApplyOptions {
6
+ source: 'webhook' | 'resync'
7
+ eventId?: string
8
+ /** `event.created` (epoch seconds) of a webhook payload; an older payload than the stored state is skipped. */
9
+ eventCreated?: number
10
+ renewal?: boolean
11
+ invoiceId?: string
12
+ trialEnding?: boolean
13
+ /** Store this status whatever the payload says (a deleted subscription is canceled). */
14
+ forced?: SubscriptionStatus
15
+ /** The paygate client — lets the first commit read the first invoice for its purchase row. */
16
+ stripe?: Stripe
17
+ }
18
+
19
+ /** Stripe subscriptions applied to a context's subscription rows. */
20
+ export interface StripeSubscriptionsHelper {
21
+ /**
22
+ * Apply one Stripe subscription — from a webhook payload or a fresh retrieval — to its row, and
23
+ * tell observers what changed. Shared by every webhook and by resync.
24
+ */
25
+ applySubscription: (subscription: Stripe.Subscription, opts: ApplyOptions) => Promise<CommitResult>
26
+ /** A subscription by id, or `null` when Stripe no longer has it. */
27
+ retrieveSubscription: (stripe: Stripe, id: string) => Promise<Stripe.Subscription | null>
28
+ /** A row whose paygate subscription no longer exists is canceled (observers hear `canceled`). */
29
+ cancelMissing: (externalId: string) => Promise<CommitResult>
30
+ /**
31
+ * Re-read paygate subscriptions — one by id, or every row of one entity — and apply each as a
32
+ * webhook would. A subscription the paygate no longer has is canceled.
33
+ *
34
+ * @returns how many rows changed
35
+ */
36
+ resyncStripeSubscription: (stripe: Stripe, ref: SubscriptionRef) => Promise<number>
37
+ /** Resync every paygate subscription that is not already terminal. Errors per row are logged. */
38
+ resyncStripeSubscriptions: (stripe: Stripe) => Promise<{ scanned: number, updated: number }>
39
+ }
@@ -0,0 +1,195 @@
1
+ import type Stripe from 'stripe'
2
+ import { SubscriptionStatus, TERMINAL_STATUSES } from '@owlmeans/payment'
3
+ import type { Context as ApiContext } from '@owlmeans/server-api'
4
+ import { memoHelper } from '@owlmeans/context'
5
+ import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
+ import type { CommitResult, PaymentSubscriptionRecord, SubscriptionRef } from '../types.js'
7
+ import type { ApplyOptions, StripeSubscriptionsHelper } from './subscriptions/types.js'
8
+ import { log } from '../log.js'
9
+ import { RESYNC_PAGE } from './consts.local.js'
10
+ import { paymentAccessOf } from '../access.js'
11
+ import { paymentUtils } from '../utils.js'
12
+ import { catalogueOf } from '../catalogue.js'
13
+ import { planHelper } from '../plan.js'
14
+ import { subscriptionCommitOf } from '../commit.js'
15
+ import { customerLockHelper } from './customer-lock.js'
16
+ import { mapStatus } from './status.js'
17
+ import { captureOf } from '../consumer/capture.js'
18
+
19
+ const isPaused = (subscription: Pick<Stripe.Subscription, 'status' | 'pause_collection'>): boolean =>
20
+ subscription.status === 'paused'
21
+ || (subscription.pause_collection != null && (subscription.status === 'active' || subscription.status === 'trialing'))
22
+
23
+ /**
24
+ * The current period. Top-level on the API version the client is pinned to; read through a narrow
25
+ * accessor because later versions move it onto the subscription items.
26
+ */
27
+ const periodOf = (subscription: Stripe.Subscription): { start?: Date, end?: Date } => {
28
+ const typed = subscription as unknown as { current_period_start?: number | null, current_period_end?: number | null }
29
+ return { start: paymentUtils.dateOf(typed.current_period_start), end: paymentUtils.dateOf(typed.current_period_end) }
30
+ }
31
+
32
+ const secondsFloor = (at: Date): Date => new Date(Math.floor(at.getTime() / 1000) * 1000)
33
+
34
+ export const makeStripeSubscriptionsHelper = (ctx: ApiContext): StripeSubscriptionsHelper => {
35
+ const access = paymentAccessOf(ctx)
36
+
37
+ const applySubscription = async (subscription: Stripe.Subscription, opts: ApplyOptions): Promise<CommitResult> => {
38
+ const metadata = subscription.metadata ?? {}
39
+ const customerId = paymentUtils.idOf(subscription.customer)
40
+ const previous = await access.subscriptions().byExternalId(subscription.id, STRIPE_PAYGATE_ALIAS)
41
+
42
+ let entityId: string | undefined = metadata.entityId ?? previous?.entityId
43
+ if (entityId == null && customerId != null) {
44
+ entityId = (await access.paygateCustomers().loadByPgId(customerId, STRIPE_PAYGATE_ALIAS))?.entityId ?? undefined
45
+ }
46
+ if (entityId == null) {
47
+ log.warn('Subscription belongs to no known entity; ignored', { subscriptionId: subscription.id })
48
+ return { record: previous, change: null, updated: false }
49
+ }
50
+ if (opts.eventId != null && previous?.lastEventId === opts.eventId) {
51
+ return { record: previous, change: null, updated: false }
52
+ }
53
+
54
+ const now = new Date()
55
+ const syncedAt = opts.eventCreated != null ? new Date(opts.eventCreated * 1000) : secondsFloor(now)
56
+ if (opts.eventCreated != null && previous?.syncedAt != null
57
+ && syncedAt.getTime() < new Date(previous.syncedAt).getTime()) {
58
+ return { record: previous, change: null, updated: false }
59
+ }
60
+
61
+ const item = subscription.items?.data?.[0]
62
+ // A price recreated by `sync.ts` (an opposite `tax_behavior`) loses its lookup key; its sku
63
+ // metadata survives, so a subscription switched to it in the portal still resolves its plan.
64
+ const planSku = item?.price?.lookup_key ?? item?.price?.metadata?.sku ?? metadata.planSku ?? previous?.planSku
65
+ if (planSku == null) {
66
+ log.warn('Subscription names no plan; ignored', { subscriptionId: subscription.id })
67
+ return { record: previous, change: null, updated: false }
68
+ }
69
+ const plan = await catalogueOf(ctx).findPlan(planSku)
70
+ const productSku = plan?.productSku ?? previous?.productSku ?? metadata.productSku ?? planSku
71
+ const paused = opts.forced == null && isPaused(subscription)
72
+ const period = periodOf(subscription)
73
+ const terminal = opts.forced != null && TERMINAL_STATUSES.includes(opts.forced)
74
+
75
+ const next = paymentUtils.compact({
76
+ ...(previous ?? {}),
77
+ entityId,
78
+ planSku,
79
+ productSku,
80
+ service: metadata.service ?? previous?.service ?? productSku,
81
+ paygate: STRIPE_PAYGATE_ALIAS,
82
+ externalId: subscription.id,
83
+ itemId: item?.id,
84
+ priceId: item?.price?.id,
85
+ status: opts.forced ?? mapStatus(subscription),
86
+ externalStatus: subscription.status,
87
+ rank: plan != null ? planHelper.planRank(plan) : previous?.rank ?? 0,
88
+ periodStart: period.start,
89
+ periodEnd: period.end,
90
+ cancelAtPeriodEnd: subscription.cancel_at_period_end === true,
91
+ canceledAt: paymentUtils.dateOf(subscription.canceled_at),
92
+ endedAt: paymentUtils.dateOf(subscription.ended_at) ?? (terminal ? previous?.endedAt ?? now : undefined),
93
+ pausedAt: paused ? previous?.pausedAt ?? now : undefined,
94
+ trialEnd: paymentUtils.dateOf(subscription.trial_end),
95
+ latestInvoiceId: opts.invoiceId ?? paymentUtils.idOf(subscription.latest_invoice) ?? previous?.latestInvoiceId,
96
+ customerId,
97
+ currency: subscription.currency?.toLowerCase() ?? previous?.currency,
98
+ createdAt: previous?.createdAt ?? paymentUtils.dateOf(subscription.created) ?? now,
99
+ updatedAt: now,
100
+ syncedAt,
101
+ }) as PaymentSubscriptionRecord
102
+ // `compact` drops every field the payload cleared — the stored record is replaced as a whole.
103
+
104
+ return await subscriptionCommitOf(ctx).commitSubscription(previous, next, {
105
+ eventId: opts.eventId, renewal: opts.renewal, invoiceId: opts.invoiceId, trialEnding: opts.trialEnding,
106
+ // The first invoice is a purchase: its window exists before an observer grants the bundle.
107
+ beforePropagate: async (record, change) => {
108
+ if (change === 'created') {
109
+ await captureOf(ctx).captureSubscriptionPurchase(opts.stripe ?? null, subscription, record)
110
+ }
111
+ },
112
+ })
113
+ }
114
+
115
+ const retrieveSubscription = async (stripe: Stripe, id: string): Promise<Stripe.Subscription | null> => {
116
+ try {
117
+ return await stripe.subscriptions.retrieve(id)
118
+ } catch (error) {
119
+ if (paymentUtils.isMissingObject(error)) {
120
+ return null
121
+ }
122
+ throw error
123
+ }
124
+ }
125
+
126
+ const cancelMissing = async (externalId: string): Promise<CommitResult> => {
127
+ const previous = await access.subscriptions().byExternalId(externalId, STRIPE_PAYGATE_ALIAS)
128
+ if (previous == null || TERMINAL_STATUSES.includes(previous.status)) {
129
+ return { record: previous, change: null, updated: false }
130
+ }
131
+ const now = new Date()
132
+
133
+ return await subscriptionCommitOf(ctx).commitSubscription(previous, {
134
+ ...previous, status: SubscriptionStatus.Canceled, endedAt: previous.endedAt ?? now, updatedAt: now,
135
+ syncedAt: secondsFloor(now),
136
+ })
137
+ }
138
+
139
+ const resyncStripeSubscription = async (stripe: Stripe, ref: SubscriptionRef): Promise<number> => {
140
+ const ids = new Set<string>()
141
+ if (ref.subscriptionId != null) {
142
+ ids.add(ref.subscriptionId)
143
+ }
144
+ if (ref.entityId != null) {
145
+ const { items } = await access.subscriptions().list({ entityId: ref.entityId, paygate: STRIPE_PAYGATE_ALIAS }, { size: 0 })
146
+ items.forEach(row => ids.add(row.externalId))
147
+ }
148
+
149
+ let updated = 0
150
+ for (const id of ids) {
151
+ const subscription = await retrieveSubscription(stripe, id)
152
+ const customerId = subscription != null ? paymentUtils.idOf(subscription.customer) : undefined
153
+ const result = await customerLockHelper.withCustomerLock(customerId, async () => subscription != null
154
+ ? await applySubscription(subscription, { source: 'resync', stripe })
155
+ : await cancelMissing(id))
156
+ if (result.updated) {
157
+ updated++
158
+ }
159
+ }
160
+
161
+ return updated
162
+ }
163
+
164
+ const resyncStripeSubscriptions = async (stripe: Stripe): Promise<{ scanned: number, updated: number }> => {
165
+ const ids: string[] = []
166
+ for (let page = 0; ; page++) {
167
+ const { items } = await access.subscriptions().list(
168
+ { paygate: STRIPE_PAYGATE_ALIAS, status: { $nin: [...TERMINAL_STATUSES] } },
169
+ { size: RESYNC_PAGE, page, sort: ['createdAt'] },
170
+ )
171
+ ids.push(...items.map(row => row.externalId))
172
+ if (items.length < RESYNC_PAGE) {
173
+ break
174
+ }
175
+ }
176
+
177
+ let updated = 0
178
+ for (const subscriptionId of ids) {
179
+ try {
180
+ updated += await resyncStripeSubscription(stripe, { subscriptionId })
181
+ } catch (error) {
182
+ log.error('Subscription resync failed', { subscriptionId, error })
183
+ }
184
+ }
185
+
186
+ return { scanned: ids.length, updated }
187
+ }
188
+
189
+ return {
190
+ applySubscription, retrieveSubscription, cancelMissing, resyncStripeSubscription, resyncStripeSubscriptions,
191
+ }
192
+ }
193
+
194
+ /** The Stripe subscriptions of a context — one per context. */
195
+ export const stripeSubscriptionsOf = memoHelper.oncePer(makeStripeSubscriptionsHelper)
@@ -0,0 +1,61 @@
1
+ import type Stripe from 'stripe'
2
+ import type { BillingProfileView, ConsumerRegion, ConsumerRightsPolicy } from '@owlmeans/payment'
3
+
4
+ export interface CacheEntry<T> { value: T; expiresAt: number }
5
+
6
+ export type TaxOutcome = { ok: true; calculation: Stripe.Tax.Calculation } | { ok: false; code?: string }
7
+
8
+ export type FxOutcome = { currency: string; exchangeRate: number; fxFeeRate?: number } | null
9
+
10
+
11
+ export interface FxQuoteResponse {
12
+ rates?: Record<string, {
13
+ exchange_rate?: number
14
+ rate_details?: { base_rate?: number; fx_fee_rate?: number; reference_rate?: number }
15
+ }>
16
+ }
17
+
18
+ export type ConfigurationParams = Stripe.BillingPortal.ConfigurationCreateParams
19
+
20
+ export type Claim = 'ours' | 'foreign' | 'unclaimed'
21
+
22
+ export interface CheckoutOptionsFlags {
23
+ /** The billing country is locked and the saved customer address carries it: never overwrite it. */
24
+ locked?: boolean
25
+ /** Adaptive Pricing is allowed on this session (the charge currency is the settlement currency). */
26
+ adaptive?: boolean
27
+ }
28
+
29
+ /** What the consumer-rights policy makes of this checkout's buyer. */
30
+ export interface BuyerContext {
31
+ policy: ConsumerRightsPolicy | null
32
+ profile: BillingProfileView | null
33
+ country?: string
34
+ region: ConsumerRegion | null
35
+ inScope: boolean
36
+ language: string
37
+ /** `null`: the policy names no region currencies — the legacy settlement behaviour. */
38
+ chargeCurrency: string | null
39
+ /**
40
+ * Checkout keeps the saved customer address (tax follows it, nothing typed at Stripe moves it): a
41
+ * locked profile, or a `stripe.lockCustomerCountry` pin, whose country it carries — tax-locatable.
42
+ */
43
+ addressLocked: boolean
44
+ /** The address is held by `stripe.lockCustomerCountry`: the first completed purchase locks THIS country. */
45
+ countryPinned: boolean
46
+ }
47
+
48
+ export interface StripeErrorShape {
49
+ type?: string
50
+ rawType?: string
51
+ code?: string
52
+ param?: string
53
+ message?: string
54
+ raw?: { type?: string, code?: string, param?: string, message?: string }
55
+ }
56
+
57
+ export interface WebhookRequest {
58
+ original?: { rawBody?: string | Buffer }
59
+ rawBody?: string | Buffer
60
+ headers: Record<string, string | string[] | undefined>
61
+ }
@@ -0,0 +1,7 @@
1
+ import type { CheckoutPlugin } from '../types.js'
2
+
3
+ /** A plugin that admitted an attempt, with the reservation it holds. */
4
+ export interface Admitted {
5
+ plugin: CheckoutPlugin
6
+ reservationId?: string
7
+ }
@@ -0,0 +1,63 @@
1
+ import type Stripe from 'stripe'
2
+ import type { CommonServiceRoute } from '@owlmeans/route'
3
+ import type { PaymentWebhookRecord } from '../../types.js'
4
+
5
+ export interface EnsureWebhookOptions {
6
+ /** Verify the stored endpoint still exists even when nothing changed locally. */
7
+ force?: boolean
8
+ }
9
+
10
+ /** A deployment's Stripe webhook: where it is served, the managed endpoint, its secrets and its deliveries. */
11
+ export interface WebhookHelper {
12
+ /** The alias whose host and base form the webhook URL: the gateway's `webhookService`, else `cfg.service`. */
13
+ webhookServiceOf: () => string
14
+ /** The key this deployment's Stripe rows are stored under: the gateway's `owner`, else `cfg.service`. */
15
+ gatewayOwnerOf: () => string
16
+ /** @throws WebhookSetupError('service:<alias>') when the webhook service is not declared in `cfg.services`. */
17
+ webhookRouteOf: (alias?: string) => CommonServiceRoute
18
+ /** This deployment's public webhook URL for a paygate, on the webhook service's host and base. */
19
+ webhookUrlOf: (paygate?: string) => string
20
+ /**
21
+ * Keep exactly one Stripe webhook endpoint for this deployment at its own URL, subscribed to
22
+ * `WEBHOOK_EVENTS` on the client's API version, and persist its signing secret — which Stripe
23
+ * returns only when an endpoint is created.
24
+ *
25
+ * A deployment's identity is its webhook URL (`webhookUrlOf`: the `webhookService` alias's host and
26
+ * base); its rows are keyed by the gateway's `owner` (`gatewayOwnerOf`). Several deployments of one
27
+ * application may share a Stripe account — a test-mode account commonly serves every non-production
28
+ * deployment — each with its own database and URL, so a deployment deletes only the endpoints its
29
+ * own `payment-webhook` rows name.
30
+ *
31
+ * - A URL Stripe cannot deliver to (not https, a loopback or dotless host) is skipped.
32
+ * - An unchanged `{ url, apiVersion, events }` fingerprint makes no paygate call at all.
33
+ * - `force` first verifies the stored endpoint still exists; one deleted from outside loses its row
34
+ * and is created again.
35
+ * - Changed events on the same API version update the endpoint in place.
36
+ * - A changed API version (create-only on an endpoint) deletes and recreates it.
37
+ * - An endpoint already at this exact URL that no row names is replaced: its secret is unknown here.
38
+ * - A row of this paygate and owner at another URL is a URL this deployment has left — a moved host,
39
+ * or a new `webhookService`: once the endpoint at the current URL is in place, the endpoint that
40
+ * row names is deleted (already gone is fine), then the row.
41
+ * - An endpoint at another URL that no row of this deployment names belongs to another deployment
42
+ * and is never deleted — whatever its metadata says.
43
+ * - Replicas racing to persist one row: the endpoint created last is the live one.
44
+ * - A created endpoint carries `{ owlmeans: 'payment', service: <owner> }` metadata and the
45
+ * `owlmeans:<owner>` description for operators.
46
+ */
47
+ ensureWebhookEndpoint: (stripe: Stripe, opts?: EnsureWebhookOptions) => Promise<PaymentWebhookRecord | null>
48
+ /**
49
+ * The secrets a Stripe signature may be verified with, in order: the configured file secret (an
50
+ * override), then the one stored for the managed endpoint — the newest row of the gateway's `owner`,
51
+ * so a process receiving the webhook finds the secret whichever process of the owner stored it.
52
+ */
53
+ stripeWebhookSecrets: () => Promise<string[]>
54
+ /** The secret a Stripe signature is verified with. @throws WebhookSetupError('secret') */
55
+ stripeWebhookSecret: () => Promise<string>
56
+ /**
57
+ * Verify a Stripe webhook against the configured override secret, then the managed endpoint's
58
+ * stored one, and dispatch it.
59
+ *
60
+ * @throws PaygateSignatureError | WebhookSetupError('secret')
61
+ */
62
+ handleStripeWebhook: (stripe: Stripe, request: unknown) => Promise<void>
63
+ }
@@ -0,0 +1,288 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type Stripe from 'stripe'
3
+ import { makeSecurityHelper } from '@owlmeans/config'
4
+ import { type CommonServiceRoute, normalizePath } from '@owlmeans/route'
5
+ import { WebhookSetupError, PaygateSignatureError } from '@owlmeans/payment'
6
+ import type { Context as ApiContext } from '@owlmeans/server-api'
7
+ 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
+ import type { PaymentWebhookRecord } from '../types.js'
12
+ import { log } from '../log.js'
13
+ import type { EnsureWebhookOptions, WebhookHelper } from './webhook-manager/types.js'
14
+ import { paymentAccessOf } from '../access.js'
15
+ import { paymentUtils } from '../utils.js'
16
+ import { paymentGate } from '../protocol.js'
17
+ import { createEventHandler } from './events.js'
18
+ import type { WebhookRequest } from './types.local.js'
19
+
20
+ /** The path the webhook route answers for one paygate: `/<base>/webhook/<paygate>`. */
21
+ const webhookPathOf = (paygate: string): string =>
22
+ '/' + normalizePath(normalizePath(paymentGate.base.route.route.path) + '/'
23
+ + normalizePath(paymentGate.webhook.route.route.path).replace(':paygate', paygate))
24
+
25
+ /** A URL a paygate can deliver to: https on a public, dotted host name. */
26
+ const isDeliverableUrl = (url: string): boolean => {
27
+ let parsed: URL
28
+ try {
29
+ parsed = new URL(url)
30
+ } catch {
31
+ return false
32
+ }
33
+ const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase()
34
+
35
+ return parsed.protocol === 'https:' && host !== 'localhost' && host !== '127.0.0.1' && host !== '::1'
36
+ && !host.endsWith('.local') && host.includes('.')
37
+ }
38
+
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
+ export const makeWebhookHelper = (ctx: ApiContext): WebhookHelper => {
47
+ const access = paymentAccessOf(ctx)
48
+
49
+ const webhookServiceOf = (): string => access.gatewayOf()?.webhookService ?? ctx.cfg.service
50
+
51
+ const gatewayOwnerOf = (): string => access.gatewayOf()?.owner ?? ctx.cfg.service
52
+
53
+ const webhookRouteOf = (alias: string = webhookServiceOf()): CommonServiceRoute => {
54
+ const route = ctx.cfg.services?.[alias] as CommonServiceRoute | undefined
55
+ if (route == null) {
56
+ throw new WebhookSetupError(`service:${alias}`)
57
+ }
58
+
59
+ return route
60
+ }
61
+
62
+ const webhookUrlOf = (paygate: string = STRIPE_PAYGATE_ALIAS): string =>
63
+ makeSecurityHelper(ctx as never).makeUrl(webhookRouteOf(), webhookPathOf(paygate))
64
+
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
+ }
132
+
133
+ const ensureWebhookEndpoint = async (
134
+ stripe: Stripe, opts: EnsureWebhookOptions = {},
135
+ ): 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' })
139
+ return null
140
+ }
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
+ }
237
+ }
238
+
239
+ return secrets
240
+ }
241
+
242
+ const stripeWebhookSecret = async (): Promise<string> => {
243
+ const [secret] = await stripeWebhookSecrets()
244
+ if (secret == null) {
245
+ throw new WebhookSetupError('secret')
246
+ }
247
+
248
+ return secret
249
+ }
250
+
251
+ const handleStripeWebhook = async (stripe: Stripe, request: unknown): Promise<void> => {
252
+ 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()
272
+ }
273
+
274
+ await createEventHandler(ctx, stripe).process(event)
275
+ }
276
+
277
+ return {
278
+ webhookServiceOf, gatewayOwnerOf, webhookRouteOf, webhookUrlOf, ensureWebhookEndpoint, stripeWebhookSecrets,
279
+ stripeWebhookSecret, handleStripeWebhook,
280
+ }
281
+ }
282
+
283
+ /** The webhook endpoint of a context — one per context. */
284
+ export const webhookOf = memoHelper.oncePer(makeWebhookHelper)
285
+
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)