@owlmeans/server-payment 0.1.18-rc.8 → 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
@@ -1,83 +1,642 @@
1
1
  ---
2
2
  name: server-payment
3
- description: Public in-process Stripe gateway for OwlMeans backends — amount and quantity checkout, subscriptions, protocol-bound webhook routes, product sync, fulfillment observers and entitlement gates. Use when wiring @owlmeans/server-payment or changing Stripe payment behavior.
3
+ description: Public in-process Stripe gateway for OwlMeans backends — amount and quantity checkout, subscriptions, the checkout plugin seam (per-entity narrowing, admission, holds), protocol-bound webhook routes, product sync with per-currency prices, fulfillment observers, entitlement gates, and the EU consumer-rights service (country lock, purchases and withdrawal windows, spend consent, subscription start requests, the withdrawal and cancellation functions with automatic refunds and credit notes, durable-medium mails, reconcile). Use when wiring @owlmeans/server-payment or changing Stripe payment behavior.
4
4
  user-invocable: false
5
5
  ---
6
6
  <!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
7
7
 
8
8
  # @owlmeans/server-payment
9
9
 
10
- **Install:** `bun add @owlmeans/server-payment@^0.1.18-rc.7`
10
+ **Install:** `bun add @owlmeans/server-payment@^0.1.18`
11
11
 
12
- Public MIT package in the common monorepo. It embeds Stripe into an application backend; the
13
- consumer owns products, credit conversion and entitlement side effects. It persists customers,
14
- subscriptions/fulfilled sessions and sync fingerprints in Mongo.
12
+ Public MIT package. It embeds Stripe into an application backend and owns everything between
13
+ Stripe and an entity's entitlements: the subscription store, one-time fulfillments, the usage
14
+ ledger of counted limits, plan resolution, the two gate services, Stripe's own configuration
15
+ (products, prices, the portal, the webhook endpoint) and the EU consumer-rights records and
16
+ functions. The application owns its catalogue, what a purchase is worth to it (credits,
17
+ provisioning), its usage meter and its side effects. Contracts — plans, limits, promos, the
18
+ entitlement view, the consumer-rights views, calculators, copy and refusals — are
19
+ `@owlmeans/payment`; the model across packages is the `entitlements` skill. Field lists, the
20
+ service contract and the step-by-step algorithms are in the `reference` part
21
+ ([parts/reference.md](parts/reference.md)).
15
22
 
16
23
  ## Wiring
17
24
 
18
25
  ```typescript
19
- stripeSecrets(cfg, { api: '/secrets/stripe-key', webhook: '/secrets/stripe-webhook' })
20
- declarePaymentProduct(cfg, { sku: 'credits', type: ProductType.Consumable,
21
- services: ['app'], name: 'Credits', taxCode: 'txcd_10103000' })
22
- declarePaymentPlan(cfg, { productSku: 'credits', sku: 'credits-unit',
23
- duration: PlanDuration.Consumable, price: 0.02,
24
- pricingMode: CheckoutPricingMode.Amount, amountPolicy })
25
-
26
- appendPaymentGatewayService(context)
27
- export const serverBindings = [...paymentGateEntrypoints]
28
- observer(context).onTopUp(async completion => { /* append an idempotent ledger event */ })
26
+ stripeSecrets(cfg, { api: '/secrets/stripe-key' }) // webhook secret: optional override
27
+ portalBranding(cfg, { returnUrl: 'https://app.example.com/billing', headline: 'Example' })
28
+ declarePaymentPricing(cfg, { // absent entirely: today's fixed behaviour, unchanged
29
+ tax: { automatic: true, behavior: TaxBehavior.Exclusive, collectTaxId: true, estimate: true },
30
+ currency: { adaptive: true, adaptiveFeeRate: 0.04, estimate: true }, // the fee is optional: see "Price sync and the tax estimate"
31
+ stripe: { settlementCurrency: 'eur', subscriptionPaymentMethodTypes: ['card', 'link', 'klarna'],
32
+ subscriptionPaymentMethodTypesByCurrency: { usd: ['card', 'link'] },
33
+ lockCustomerEmail: true, lockCustomerCountry: true }, // optional: see "Customer locks"
34
+ })
35
+ declareConsumerRights(cfg, { // absent: no consumer-rights behaviour at all
36
+ textVersion: 'terms-2026-09', links: { en: { billingTerms, withdrawalInformation, withdrawalFunction, cancellation } },
37
+ currencies: { eu: 'eur', other: 'usd' },
38
+ mechanisms: { countryLock: true, checkoutTerms: true, performanceConsent: true, subscriptionStart: true,
39
+ withdrawal: true, automaticRefunds: true, cancellation: true, purchaseConfirmation: true },
40
+ trader: { name: 'Example', legalName: 'Example Ltd', address: '…', email: 'support@example.com' },
41
+ mail: { from: 'billing@example.com', bcc: ['archive@example.com'] }, // alias: default MAILER_SERVICE
42
+ consentContext: 'included', // optional: the `_included` consent copy variant
43
+ })
44
+ declarePaymentProduct(cfg, { sku: 'app-plans', type: ProductType.Service, services: ['app'], name: 'Plans' })
45
+ declarePaymentPlan(cfg, { productSku: 'app-plans', sku: 'free', rank: 0, free: true, price: 0, … })
46
+ declarePaymentPlan(cfg, { productSku: 'app-plans', sku: 'pro-monthly', rank: 10, price: 20,
47
+ recurring: { interval: 'month' }, currencyPrices: { usd: 20 },
48
+ withdrawal: { components: [{ key: 'services', basis: 'time', shareMinor: 1000 },
49
+ { key: 'credits', basis: 'units', shareMinor: 1000 }] }, capabilities: […] })
50
+
51
+ appendPaymentGatewayService(context) // the process that talks to Stripe
52
+ appendPaymentGatewayService(context, { manage: false }) // a worker that only reads entitlements and asserts consent
53
+ // One deployment, several managed processes on one database: the same owner and webhookService everywhere
54
+ appendPaymentGatewayService(context, { owner: 'app-api', webhookService: 'app-hooks' }) // receives the webhook, bootstraps at boot
55
+ appendPaymentGatewayService(context, { owner: 'app-api', webhookService: 'app-hooks', bootstrap: false }) // checkout and portal only
56
+ appendConsumerRights(context, { manage, usage: myUsageMeter }) // before or after the gateway; idempotent
57
+ paymentAccessOf(context).consumerRights().useMailRenderer(myRenderer) // lazy service: works while wiring
58
+ paymentAccessOf(context).gateway().use(myCheckoutPlugin) // a tier / cap / hold plugin — once the context is initialized
59
+ export const serverBindings = [
60
+ ...paymentGateEntrypoints, // the library's own, unpinned `paymentGate`
61
+ ...consumerRightsEntrypoints(consumerProtocols, { guardMoney, throttle, subjectOf, planNameOf }),
62
+ ...checkoutReadEntrypoints(checkoutProtocols),
63
+ ]
64
+ // …or the gate re-declared by the application (its aliases, pinned to its service, the library's paths):
65
+ export const hookBindings = [
66
+ bind(own.base),
67
+ bind(own.webhook, paymentGateHandlers.webhook),
68
+ bind(own.resync, paymentGateHandlers.resync),
69
+ bind(own.resyncSubscriptions, paymentGateHandlers.resyncSubscriptions),
70
+ ]
71
+ paymentAccessOf(context).observer().onSubscription(async event => { /* keyed by event.eventKey */ })
29
72
  ```
30
73
 
31
- `declarePaymentPlan` validates amount and quantity policies immediately. An amount plan requires
32
- `amountPolicy`; a quantity/legacy plan may declare `quantityPolicy` or the legacy min/default/max
33
- fields. `gateway(ctx).createLink(...)` takes the stable internal `entityId`; an authenticated public
34
- handler must resolve that id from its request entity before calling the in-process service.
74
+ - `appendPaymentGatewayService` registers twelve resources, the catalogue service
75
+ (`PAYMENT_SERVICE`), the completion observer, the gateway (`GATEWAY_SERVICE`), the capability
76
+ gate (`ENTITLEMENT_GATE`), the limit gate (`LIMIT_GATE`), the entitlement service
77
+ (`ENTITLEMENT_SERVICE`) and the consumer-rights service (`CONSUMER_RIGHTS_SERVICE`), each only
78
+ when not registered already. `appendConsumerRights` does the consumer-rights part alone.
79
+ - **Registration order is free.** Whichever of `appendConsumerRights` and the gateway comes first,
80
+ `usage` and `stripe` are installed on the one service, and `manage` resolves as the application's
81
+ explicit value, else the gateway's, else managed. The consumer-rights resources keep the aliases
82
+ of the first registration.
83
+ - **The consumer-rights service is lazy** (like the completion observer): `paymentAccessOf(ctx).consumerRights()`,
84
+ `useMeter` and `useMailRenderer` work while the application is wired; the gateway's initialization
85
+ initializes it, so its boot checks still run at boot. The gateway is NOT lazy: `paymentAccessOf(ctx).gateway()` (and
86
+ `.use(plugin)`) needs the initialized context.
87
+ - **`manage: false`** registers the same surface with no Stripe client: no bootstrap at init, and
88
+ `createLink`, `portalLink`, `resyncSubscription`, `resyncAll`, the webhook route, `withdraw` and
89
+ `cancel` throw `PaygateError('unmanaged')`. `grantInternalPlan`, the entitlement service,
90
+ `amountPolicy`, `planPrices` and the consumer-rights reads, `recordConsent`,
91
+ `recordStartRequest` and `assertConsent` work, because they are Mongo only.
92
+ - **Three keys of a deployment's Stripe state**, each a `PaymentGatewayOptions` field, each read
93
+ back on the gateway (`paymentAccessOf(ctx).gateway().webhookService / owner / bootstrap`):
94
+ - `webhookService` (default `cfg.service`) — the `cfg.services` alias whose host and base form
95
+ `webhookOf(ctx).webhookUrlOf`, the portal's deployment key too. Name the process that RECEIVES the webhook
96
+ (the one serving `paymentGate`) in every process, so every bootstrap computes one URL.
97
+ - `owner` (default `cfg.service`) — the `payment-webhook` rows' `service`, the signing-secret
98
+ lookup, the endpoint's `owlmeans:<owner>` description and `service` metadata, the
99
+ `portal:<owner>` fingerprint and the portal's `service` metadata. One value in every process of
100
+ the database, so each finds and replaces the others' rows.
101
+ - `bootstrap` (default: `manage`) — run `stripeBootstrapOf(ctx).bootstrapStripe` at boot. Exactly one kind of process
102
+ keeps it (the receiver). A managed process with `bootstrap: false` still serves checkout, the
103
+ portal, estimates, the resyncs and the webhook route, and a FORCED bootstrap (`resync`, an
104
+ application's maintenance `stripeBootstrapOf(ctx).bootstrapStripe(stripe, { force: true })`) still runs there —
105
+ same URL, same rows, fingerprinted, so idempotent from any process.
106
+ - Refused at construction: `bootstrap: true` with `manage: false`, an empty `owner` or
107
+ `webhookService` (`PaygateError`). A managed, bootstrapping gateway fails its initialization when
108
+ `webhookService` is not declared in `cfg.services` (`WebhookSetupError('service:<alias>')`).
109
+ - `stripe` (a `StripeFactory`, default `paymentAccessOf(ctx).stripeClient`) is the gateway's own Stripe client —
110
+ `paymentAccessOf(ctx).gateway().stripe(ctx)`, used by its methods, its boot bootstrap and the `paymentGate` handlers.
111
+ The consumer-rights service takes its own (`appendConsumerRights({ stripe })`).
112
+ - Every process that registers the gateway runs the collection validators (`collMod`) of all
113
+ twelve records at init: a process of an older version narrows the validators again, so roll
114
+ the processes of one deployment out together.
115
+ - Gateway methods take the stable `entityId`. A public handler resolves it from its request
116
+ entity first; protocol bodies carry `entitySlug`.
117
+ - A value in `stripeSecrets` / `portalBranding` that starts with `/` is read from that file at
118
+ boot, and a missing file fails the boot — so leave `webhook` out unless the file exists.
119
+
120
+ ## Declaring plans
121
+
122
+ - **`rank`** orders a product's plans; a higher rank is an upgrade. A safe integer `>= 0`; absent
123
+ reads as `0`.
124
+ - **The free plan is a plan**: `free: true`, `price: 0`, no `gateways`. It is never synchronized to
125
+ Stripe and never checked out; an entity without an entitling subscription resolves to it.
126
+ - `gateways` names the paygates a plan is sold through; absent inherits the product's.
127
+ - **`currencyPrices`** (`{ usd: 20 }`, major units, lowercase codes) are exact prices in further
128
+ currencies, synced as the reusable Price's `currency_options`; a declared price in the Price's
129
+ default currency replaces its converted amount. Only for recurring and quantity plans.
130
+ - **`withdrawal.components`** state the separately priced parts of a subscription for a withdrawal
131
+ (CJEU C-641/19): `{ key, basis: 'time' | 'units', shareMinor }`, the shares summing to
132
+ `round(price × 100)`. Absent: the whole price is one `time` component. They also pick the start
133
+ statement: a `units` part → the `_units` variant, otherwise the base (time-only) texts
134
+ (`consumerCopyHelper.startContextOf`, `@owlmeans/payment`).
135
+ - `declarePaymentPlan` refuses before recording: a bad rank or a priced/gatewayed free plan
136
+ (`PlanRankConflict`), a capability set under the reserved `limit` scope, a malformed limit
137
+ (`LimitMisdeclared('<key>:<reason>')`), a malformed or amount-mode `currencyPrices` or components
138
+ that do not add up (`ProductError('currency-prices:…' | 'withdrawal:<sku>:…')`).
139
+ - `makePlanDeclarationsModel(cfg).assertPlans()` runs when the gateway initializes and fails the boot on two free plans
140
+ at one rank, or two paid non-consumable plans of one product at one rank.
141
+ - A limit key may use a different kind on different plans; each kind counts separately and a
142
+ lifetime count stays with the entity through upgrades, downgrades and cancellations.
143
+
144
+ ## Records
145
+
146
+ None declares an ObjectId reference: `entityId` is an organization key and every other id is Stripe's.
147
+
148
+ | Collection | One row per | Indexes |
149
+ |---|---|---|
150
+ | `payment-paygate-customer` | Stripe customer (`country`, `currency` from its webhooks; `deletedAt`) | `{paygate, externalId}` unique · `{paygate, entityId}` · `{paygate, profileId}` |
151
+ | `payment-subscription` | subscription: `sub_…`, `free:<entityId>`, `internal:<planSku>:<entityId>` (+ `currency` and the checkout evidence) | `{paygate, externalId}` unique · `{entityId, status, rank:-1}` · `{entityId, planSku}` · `{paygate, customerId}` · `{paygate, itemId}` sparse · `{paygate, status, updatedAt}` |
152
+ | `payment-fulfillment` | one-time checkout session (+ evidence: country, e-mail, totals, terms, `purchaseId`) | `{paygate, externalId}` unique · `{paygate, paymentIntentId}` sparse · `{paygate, chargeId}` sparse · `{entityId, createdAt:-1}` |
153
+ | `payment-webhook` | managed webhook endpoint of an owner (`service` = the gateway's `owner`; `secret` is `secure: true`) | `{paygate, service, url}` unique |
154
+ | `payment-usage` | usage event — the ledger | `{entityId, limitKey, eventKey}` unique · `{entityId, limitKey, window}` · `{entityId, limitKey, ref}` sparse · `{entityId, createdAt:-1}` |
155
+ | `payment-usage-counter` | (entity, limit, window) projection | `{entityId, limitKey, window}` unique |
156
+ | `payment-fingerprint` | synchronized product (`<productSku>`, with `prices[]`) or portal (`portal:<owner>`) | `{sku}` unique |
157
+ | `payment-billing-profile` | organization: the billing country fixed at the first purchase | `{entityId}` unique · `{paygate, customerId}` sparse |
158
+ | `payment-purchase` | purchase = contract + withdrawal window (a paid one-time checkout, a subscription's first invoice) | `{purchaseId}` unique · `{contractRef}` unique · `{entityId, deadline:-1}` · `{entityId, purchasedAt:-1}` · `{sessionId}` unique sparse · `{paygate, subscriptionId}` · `{invoiceId}` · `{invoiceNumber}` · `{paygate, paymentIntentId}` |
159
+ | `payment-consumer-consent` | append-only: a performance consent or a subscription start request | `{entityId, decidedAt:-1}` · `{kind, entityId, planSku, decidedAt:-1}` |
160
+ | `payment-consumer-declaration` | append-only: a withdrawal or cancellation declaration | `{kind, receivedAt:-1}` · `{entityId, receivedAt:-1}` sparse · `{purchaseId}` sparse |
161
+ | `payment-consumer-event` | append-only: one execution or audit step (mail, refund, lock …) | `{recordId, at}` · `{entityId, at:-1}` sparse · `{action, ok, at}` |
162
+
163
+ - Every stored property is declared in the record schema (`additionalProperties: false`): the
164
+ resource writes a property its schema does not know as a string, and the collection validator
165
+ rejects it. New fields on existing records are optional, so old rows stay valid.
166
+ - **A map is stored as an array** (`prices[].options: [{ currency, unitAmount }]`): the resource
167
+ coerces a currency-keyed map's values to strings.
168
+ - A compound sparse index still indexes a row that lacks only some of its keys — a unique index
169
+ that must skip absent values is single-field (`{sessionId}`).
170
+ - Conditional writes (`consentedAt`, `withdrawnAt`) are raw `$set`s guarded by the old value
171
+ (`paymentUtils.conditionalSet`), so a concurrent declaration of the same purchase loses; declarations,
172
+ consents and events are only ever created.
173
+
174
+ ## Checkout
175
+
176
+ - `Amount`: one inline `price_data` item for the synchronized product, quantity 1, its
177
+ `tax_behavior` the declared `PricingPolicy.tax.behavior`, no promotion codes. `Quantity`: the
178
+ reusable price under the plan lookup key, adjustable quantity. Subscription: `planSku` (else the
179
+ product's first recurring plan), quantity 1. One-time Sessions enable `invoice_creation`.
180
+ - `CreateLinkParams.locale` is a caller-validated Stripe locale (Session `locale`, the Customer's
181
+ `preferred_locales`). `submitText` is trusted application copy — a string, or a function of
182
+ `CheckoutTextContext {language, currency, unitAmountMinor, interval, region, country}` — on
183
+ every mode; never caller-provided text.
184
+ - A plan the paygate does not sell is refused (`ProductError`). `checkoutOptions` puts automatic
185
+ tax, billing address collection, tax-id collection and Adaptive Pricing on the session exactly
186
+ as `PricingPolicy` declares them.
187
+ - Subscription methods come from `stripe.subscriptionPaymentMethodTypesByCurrency[chargeCurrency]`,
188
+ falling back to `subscriptionPaymentMethodTypes`; with neither, Stripe selects dynamically.
189
+ Currency keys and method names normalize to lowercase. Currency keys must have three letters;
190
+ method lists must be nonempty and unique. Choose account-supported methods for each currency:
191
+ a method the account cannot accept in that currency rejects the whole session.
192
+ - **Without a consumer-rights policy every session is what it always was**: the charge currency
193
+ is the settlement currency (FX from the catalogue), Adaptive Pricing as declared.
194
+
195
+ ### Under a consumer-rights policy
196
+
197
+ - **The country.** A locked billing profile overrides `params.country`; another declared country is
198
+ `BillingCountryLocked` (409), and so is a saved customer address that left the locked country
199
+ (an operator relocks). An organization that already paid before its country was locked is
200
+ locked lazily from its Stripe customer's address (`source: 'customer'`). Before any lock, the
201
+ declared country is prefilled on a customer without an address.
202
+ - **The currency.** Charge currency = the profile's currency, else `consumerRegionHelper.chargeCurrencyOf(region)`
203
+ (`policy.currencies`). An amount checkout whose policy currency IS the charge currency is
204
+ charged exactly — no FX call; any other goes through the FX reference rate (rounded up). A
205
+ subscription or quantity session is forced to the charge currency (`currency`) only when its
206
+ synced Price carries it (default or option) — otherwise it is left to Stripe and warned.
207
+ `adaptive_pricing.enabled` is explicitly true only when the policy enables it and the charge
208
+ currency is the settlement currency; every other session sends false. Omitting the flag lets
209
+ Stripe inherit the Dashboard setting and can enable localization for an exact USD checkout.
210
+ - **The lock at Stripe.** A locked profile whose customer carries the address:
211
+ `customer_update.address: 'never'` and `billing_address_collection: 'auto'` (tax follows the
212
+ saved address, Checkout cannot move it); `name: 'auto'` stays. A locked customer without a
213
+ tax-locatable address (`stripeSessionHelper.isTaxLocatable`) keeps `'auto'`/`'required'`, or Stripe refuses the
214
+ session ("Automatic tax calculation in Checkout requires a valid address on the Customer").
215
+ - **Terms.** `mechanisms.checkoutTerms` puts `consent_collection.terms_of_service: 'required'` and
216
+ `custom_text.terms_of_service_acceptance` (the `checkout.terms-acceptance.in-scope | other` copy
217
+ with the billing language's links, ≤ 1200 characters) on every session.
218
+ - **A missing Dashboard terms URL never breaks a payment.** Stripe refuses the checkbox then
219
+ (`invalid_request_error`, param `consent_collection[terms_of_service]`, "You cannot collect consent
220
+ to your terms of service unless a URL is set in the Stripe Dashboard", matched by
221
+ `stripeSessionHelper.isMissingTermsUrl`): the session is created ONCE more without `consent_collection` and without the
222
+ terms text, under the same plugin admissions, metadata `termsCollected: 'false'`; a
223
+ `checkout-terms-fallback` event (`recordKind: 'checkout'`, `recordId` = the entity, `externalId`
224
+ = the session, `ok: false`, the Stripe message in `detail`) is appended per fallback and one
225
+ `warn` log per context tells the operator what to set. Any other refusal is not retried; a
226
+ failing retry releases the admissions and propagates its own error.
227
+ - **Texts.** An in-scope top-up without `submitText` says what it buys (`checkout.top-up`, with the
228
+ country's name); a subscription without `submitText` shows the renewal price in the charge
229
+ currency (`checkout.renewal.<interval>`), and `after_submit` links the cancellation page while
230
+ that mechanism is on. Every text is asserted ≤ 1200 characters.
231
+ - **Start requests.** A subscription needs a fresh start request bound to the organization, the
232
+ plan and the current text version (`assertStartRequest` → `SubscriptionStartRequired`, 428),
233
+ unless the organization is already locked outside the territories — a country picked before
234
+ checkout may differ from the address typed at Stripe.
235
+ - **Metadata** (session and `subscription_data`): `region`, `country`, `language`, `termsVersion`,
236
+ `copyVersion`, `termsCollected` (`'true'` when the checkbox is on the session, `'false'` when the
237
+ policy has it off or after the fallback), `ipCountry` (the `cf-ipcountry` the app passes),
238
+ `startRequestId`, `profileId`, `countryPinned` (`'true'` only under `lockCustomerCountry` when the
239
+ session kept the pinned address). The purchase's `termsAccepted` comes only from the completed
240
+ session's `consent.terms_of_service` — absent when nothing was collected.
241
+
242
+ ### Customer locks (`declarePaymentPricing` → `stripe`)
243
+
244
+ Both are opt-in, backend-only, read per call from the Stripe pricing plugin config, and work with
245
+ or without a consumer-rights policy.
246
+
247
+ - **`lockCustomerEmail`** — every `createLink` must pass `CreateLinkParams.email` (the application's
248
+ verified e-mail of the buyer), else `PaygateError('customer-email')` before any Stripe call. It is
249
+ written to the Stripe customer (created with it, or updated — case-insensitively different — in
250
+ the same call as `preferred_locales`), never as `customer_email`: Checkout shows a customer's
251
+ valid e-mail read-only, and only while the customer has none asks for one and saves it. The
252
+ customer carries the LAST payer's e-mail (invoices and renewals go there). Without the lock
253
+ `email` is ignored.
254
+ - **`lockCustomerCountry`** — the known country (the locked profile's, else `params.country`) is
255
+ written to the customer as a country-only address (lines and postal code cleared) when the saved
256
+ one carries no or another country — over another country only before any lock (a locked
257
+ customer's other country is still `BillingCountryLocked`). When the saved address is
258
+ tax-locatable the session keeps it (`customer_update.address: 'never'`, collection `'auto'`):
259
+ no address form, tax on the pinned country; Stripe still shows the card form's "Country or
260
+ region" picker (a payment-method detail no parameter hides), which then moves neither tax nor the
261
+ saved address. Metadata `countryPinned: 'true'` makes the first completed purchase lock THAT
262
+ country (`lockFromSession`: `metadata.country` before `customer_details.address.country`).
263
+ - **Tax-locatable** (`stripeSessionHelper.isTaxLocatable`, from Stripe's customer-locations table): a country alone
264
+ everywhere except US (needs `postal_code`) and CA / IN (`postal_code` or `state`). A pinned US,
265
+ CA or IN customer without one is not kept: Checkout collects the address — country editable —
266
+ and the purchase locks what was typed, as without the option.
267
+ - **The portal** never offers `email` under `lockCustomerEmail`, nor `address` under
268
+ `lockCustomerCountry` (or `countryLock`); both flags are in its fingerprint.
269
+
270
+ ## Checkout plugins
271
+
272
+ `paymentAccessOf(ctx).gateway().use(plugin)` seats a `CheckoutPlugin` per gateway instance (the `ExecutionService.use`
273
+ registry: a plugin whose `alias` is registered already replaces it). All hooks are optional:
274
+
275
+ | Hook | Called | Contract |
276
+ |---|---|---|
277
+ | `narrow(ctx, {entityId, productSku, planSku?, base, at})` | every amount checkout and every `gateway.amountPolicy` | answers an `AmountNarrowing` or `null`; a throw fails the checkout closed |
278
+ | `admit(ctx, CheckoutAttempt)` | before the session, every mode | throw (`CheckoutLimitExceeded`) to veto; may return `{ reservationId }` |
279
+ | `created(ctx, CheckoutCreated)` | after the session | gets `sessionId`, `url`, `expiresAt`, amounts, its own `reservationId`; a throw expires the session, releases every hold and propagates |
280
+ | `settled(ctx, CheckoutSettled)` | webhook: `paid`, `expired`, `failed`; and `failed` for a checkout that never became usable | errors are logged, never raised |
281
+ | `sessionTtlSeconds` | — | the smallest declared, clamped to 30 min – 24 h, becomes `expires_at`; none declared: Stripe's default |
282
+
283
+ - **One narrowing path.** `createLink` and `gateway.amountPolicy(ctx, entityId, productSku,
284
+ planSku?)` both call `checkoutPluginsOf(ctx).narrowAmountFor` → `amountNarrowingHelper.narrowAmountPolicy` (`@owlmeans/payment`); an amount
285
+ above the narrowed maximum, or any amount while `blocked`, is `CheckoutLimitExceeded` (409). A
286
+ control and a refusal cannot disagree. An amount above the plan's own maximum stays the base
287
+ policy's error.
288
+ - A veto, a Stripe refusal or a throwing `created` releases what the earlier plugins admitted
289
+ (`settled` with `outcome: 'failed'` and their `reservationId`).
290
+ - `gateway.planPrices(ctx, productSku)` answers `PlanPriceView[]` (a default entry per Price plus
291
+ one per currency option) from the synced fingerprint rows — no Stripe call.
292
+
293
+ ## Price sync and the tax estimate
294
+
295
+ - `productSyncOf(ctx).syncStripeProducts` gives a matching, still-`unspecified` price the declared `tax.behavior` IN
296
+ PLACE and a fresh one on creation; a price carrying the OPPOSITE behavior is replaced. Before an
297
+ in-place update it checks the account's tax-settings default and skips — logging why — when that
298
+ would change existing renewals, unless `stripe.migrateUnspecifiedPrices` opts in.
299
+ - A recurring or quantity plan whose catalogue currency differs from `stripe.settlementCurrency` is
300
+ converted with an unlocked FX Quote (`reference_rate`, rounded up). Its **currency options**:
301
+ the declared `currencyPrices`, plus the catalogue currency (exact `round(price × 100)`) when it is
302
+ one of the policy's region currencies; each option carries the declared `tax_behavior`. Active
303
+ prices are listed with `expand: ['data.currency_options']`; a changed option replaces the Price
304
+ (deactivate + create with `transfer_lookup_key`) — options are never edited in place, so a
305
+ subscriber keeps the Price they accepted.
306
+ - The resolved amounts, currencies and options are fingerprinted; an unchanged fingerprint makes no
307
+ product/price call. Each sync stores the product's `prices[]` (`SyncedPrice`: price id, lookup
308
+ key, default currency and amount, options, tax behavior, interval, source amount) on the
309
+ fingerprint row — what `planPrices`, checkout currency forcing and the estimate read. A row from
310
+ before `prices[]` existed syncs once more.
311
+ - `estimatePrice` (`plugins/estimate.ts`) is a Stripe Tax calculation for one product/plan's
312
+ reference amount at a country — **$0.05 per distinct** (currency, country, amount, tax code,
313
+ behavior, matching tax ids) combination, cached per gateway-service instance for 24h; failures
314
+ are never cached. **A locked profile overrides the requested country** (`source: 'profile'`,
315
+ `locked: true`); the estimate carries `region`. Under a policy with region currencies a
316
+ recurring plan is estimated in the charge currency at its synced unit amount (default or
317
+ option); the `local` line (FX Quotes, a PREVIEW endpoint) only when the session's CHARGE currency
318
+ (the region's, or the locked profile's) is the settlement currency — the same test the session's
319
+ `adaptive_pricing` takes. An amount plan stays estimated in its policy currency but is charged in
320
+ the region's currency, so an EU top-up gets its local line through the policy → settlement →
321
+ local chain, and an exact-USD one none.
322
+ - **The local line prices the conversion the way Checkout does.** Adaptive Pricing shows a buyer's
323
+ currency at the quote's `base_rate` plus its own conversion fee (`price × (1 + fee)`, Stripe's 2–4%,
324
+ decided per currency — test mode showed 4% for PLN: `1 EUR = 4.5626 PLN = 1 / 0.227941 × 1.04`),
325
+ while the FX Quotes `exchange_rate` is `base_rate × (1 − fx_fee_rate)` with the quote's 2% — so it
326
+ understates Checkout (99.11 against 101.02 PLN for a €22.14 total). `currency.adaptiveFeeRate`
327
+ declares that fee: `local.exchangeRate` = `base_rate / (1 + fee)` (and `fxFeeRate` = the fee),
328
+ divided by the source's reference rate for an amount plan, so a subscription and a top-up share the
329
+ one rule. Absent, `local.exchangeRate` is the quote's own `exchange_rate`. A buyer whose local
330
+ currency IS the settlement currency pays no conversion fee and gets none. `StripeFxRate.baseRate`
331
+ is `rate_details.base_rate` (derived from `exchange_rate` and `fx_fee_rate` when absent); the fee
332
+ is part of the FX cache key. The fee Stripe really applies is not exposed by any API — probe it by
333
+ reading a test-mode Checkout page ("includes N% conversion fee") and set the declared value.
35
334
 
36
- ## Checkout modes
335
+ ## The subscription store
37
336
 
38
- - `Amount`: validate `amountMinor`, compute `chargeAmountMinor`, create one inline
39
- `price_data` item for the synchronized Stripe Product, quantity 1, tax-exclusive, with no
40
- adjustable quantity and no promotion codes. No reusable Stripe Price is created; a superseded
41
- quantity Price under the plan lookup key is deactivated.
42
- - `Quantity`: load the reusable Stripe Price and create an adjustable item from the quantity
43
- policy. This remains supported so existing consumers and already-open Checkout sessions work.
44
- - Subscription: reusable recurring Stripe Price, quantity 1, with billing portal management.
337
+ - **The effective plan** is the highest-ranked row in `ENTITLING_STATUSES` (catalogue rank; the
338
+ newest on a tie), else the declared free plan, else `PlanRequired`.
339
+ - **A subscription row may override its plan.** `PaymentSubscriptionRecord.overrides`
340
+ (`SubscriptionOverrides`: `limits: { <key>: { limit } }`) is applied by `planHelper.overriddenPlan(plan, row)`
341
+ inside `resolveEffectivePlan` and `snapshotOf`, so ceilings, the entitlement view, both gates and
342
+ observers read one answer and nothing else needs to know. An override sets the ceiling of a key
343
+ the plan declares and drops that key's promo; kind and window stay the plan's (counters are keyed
344
+ by them); an undeclared key or a ceiling that is not a safe integer `>= 0` is ignored. An operator
345
+ writes it, no paygate does: every sync and re-grant spreads the previous row, so it survives. It
346
+ belongs to the row — it follows the subscription through a plan change, ends with it, and the
347
+ free-plan fallback (no row) has none. A new overridable parameter is a new optional key of
348
+ `SubscriptionOverrides`, declared in `PaymentSubscriptionSchema` and merged in `planHelper.overriddenPlan`.
349
+ - `mapStatus`: `active`→Active, `trialing`→Trial, `past_due`→PastDue, `unpaid`/`paused`→Suspended,
350
+ `incomplete`→Created, `incomplete_expired`→Ended, `canceled`→Canceled; paused collection is
351
+ Suspended with `pausedAt`.
352
+ - **State is written before observers, and classified against what observers were last told**
353
+ (`propagated`, stamped with `lastEventId` only after every observer succeeded).
354
+ `CommitOptions.beforePropagate(record, change)` runs between the write and the observers — the
355
+ Stripe path writes a subscription's purchase there on `created`, so the window exists before an
356
+ observer grants the bundle.
357
+ - Classification, first match: `created` · `canceled` · `paused` · `resumed` · `upgraded` /
358
+ `downgraded` · `cancel-scheduled` · `cancel-undone` · `renewed` (once per invoice) · `past-due` ·
359
+ `suspended` · `trial-ending`.
360
+ - A repeated delivery (`lastEventId`) is ignored; an older payload than the stored state is not
361
+ applied. `grantInternalPlan(ctx, entityId, planSku, { force?, periodEnd? })` upserts an internal
362
+ row; `resyncSubscription` / `resyncAll` re-read and apply as a webhook would.
45
363
 
46
- Every session enables automatic tax, billing address and tax-id collection. Amount metadata carries
47
- pricing mode, net amount, adjusted pre-tax subtotal, currency, product, plan, service and owner.
364
+ ## The usage ledger
48
365
 
49
- ## Fulfillment
366
+ `payment-usage` events are the source of truth; `payment-usage-counter` is the projection that
367
+ admission reads. `consume` increments the counter FIRST by one conditional upsert (`used <= limit
368
+ - amount`), then appends the event — **the counter may over-count, never over-admit**. An event
369
+ key is idempotent; `release` appends `release:<eventKey>` first. `reconcileCounters`,
370
+ `reconcileOccupancy`, `reconcileOf(ctx).reconcileEntity` and `.reconcileAll` repair it (details: the `entitlements`
371
+ skill).
50
372
 
51
- Handle both `checkout.session.completed` and `checkout.session.async_payment_succeeded`, but grant
52
- nothing until `payment_status === 'paid'`. Amount fulfillment compares Stripe currency and actual
53
- `amount_subtotal` with the server-created metadata. Completion is discriminated:
373
+ ## Entitlements and gates
54
374
 
55
- - `{ mode: 'amount', amountMinor, chargeAmountMinor, currency, ... }`
56
- - `{ mode: 'quantity', units, ... }`
375
+ - `paymentAccessOf(ctx).entitlements()` → `effectivePlan`, `entitlements` (the `EntitlementView`), `hasCapability`,
376
+ `limitState`, the ledger operations. Never calls Stripe.
377
+ - **Capability gate** (`ENTITLEMENT_GATE`) passes when the view grants ANY parameter; **limit gate**
378
+ (`LIMIT_GATE`) when any `limit:<key>[>=n]` has room — it never consumes. Both refuse with
379
+ `AuthForbidden` refusals (403) and fail closed on an unreadable store.
380
+ - The consumer-rights refusals (428/409) and `CheckoutLimitExceeded` are not entitlement refusals.
57
381
 
58
- The session id is `externalId`. A pending fulfillment record is created before calling observers
59
- and gets `fulfilledAt` only after they succeed; observer failures escape so Stripe retries. Consumer
60
- callbacks must still use `externalId` as their own append-only event key, covering a crash after the
61
- side effect and before `fulfilledAt`. A session without pricing-mode metadata is a legacy quantity
62
- session and remains fulfillable.
382
+ ## Consumer rights
63
383
 
64
- Subscription observers receive `{ isNew, status, capabilities, limits, ... }`. One-time bundles go
65
- behind `isNew` and use an idempotent external event key. Status updates and entitlement provisioning
66
- must be safe to repeat.
384
+ The EU right of withdrawal (with the Art. 11a withdrawal function), spend consent for prepaid
385
+ credits, subscription start requests, the cancellation function and a billing country fixed at the
386
+ first purchase. The service is `paymentAccessOf(ctx).consumerRights()` (`.consumerRightsOf()` is null-safe); its
387
+ full contract is in the `reference` part ([parts/reference.md](parts/reference.md)).
67
388
 
68
- ## Protocols and security
389
+ - **A purchase** is a paid one-time checkout, or a subscription's FIRST invoice — renewals,
390
+ internal grants and manual credits never are. Its row (`purchaseId` `stripe:<cs_…>` /
391
+ `stripe:<sub_…>`, `contractRef` `CR-YYMMDD-XXXXXX` over an unambiguous alphabet, retried on a
392
+ collision) is written **before anything is granted**: in `checkout.session.completed` before
393
+ `onTopUp`, in the first subscription commit before the `created` observers. A completed
394
+ subscription checkout then refines it with the buyer's own country, e-mail, totals and terms
395
+ acceptance. Window = in scope, before `deadline` (`withdrawalDeadlineHelper.withdrawalDeadlineOf`, policy margin),
396
+ neither withdrawn nor refunded; a full refund closes it (`refundedAt`).
397
+ - **In scope** when the buyer's own country or the organization's locked country is in the policy's
398
+ territories; an unknown country is protected by default. A business tax id does not exempt.
399
+ - **The lock**: the first completed purchase's `customer_details.address.country` (else the
400
+ declared one) locks the profile — first write wins through the unique index; a later different
401
+ country is a `lock-mismatch` event, never a relock. The request's `cf-ipcountry` is stored as
402
+ `ipCountry` beside it, and the `lock` event flags `ipMismatch`. The profile's currency is an
403
+ entitling Stripe subscription's currency when one exists (two subscriptions of one customer can
404
+ not differ), else the region's. Only `lock(entityId, country, 'manual', { force: true, by,
405
+ reason })` replaces a lock, audited as `relock`.
406
+ - **Unlock** (an operator, Mongo only — unmanaged works): `unlock(entityId, { by, reason })` deletes
407
+ the profile (only while it still holds the country read) and appends an `unlock` event carrying the
408
+ whole row; it answers the profile as it was, or `null`. After an unlock no lock is taken from the
409
+ paygate customer's saved address — neither at checkout nor by `reconcile` — so the next COMPLETED
410
+ purchase locks the country again from its own address.
411
+ - **Performance consent** (top-ups only — a start request covers a subscription's own invoice):
412
+ required while an open in-scope top-up window has none. `assertConsent` is one indexed query and
413
+ throws `PerformanceConsentRequired` (428, `pending`, latest `deadline`); an application calls it
414
+ only where credits will actually be spent. `consentView` carries the policy's `consentContext`
415
+ as `context`. `recordConsent` renders the statement itself (`consumerCopyHelper.consentStatementOf` with the
416
+ trader's `name` and the policy's `consentContext`, so the stored verbatim text and the consent
417
+ mail are the `_<context>` variant the dialog showed; without a context the base statement),
418
+ stores that `context` on the record, refuses a stale `textVersion` with a fresh 428, covers only
419
+ the open windows the body lists, stamps `consentedAt` conditionally, mails the confirmation, then
420
+ tells `onConsent`.
421
+ - **Start requests follow the plan's withdrawal arithmetic.** `startView(entityId, planSku)` names
422
+ `context = consumerCopyHelper.startContextOf(plan)` (`'units'` for a plan with a `units` component, absent for a
423
+ time-only one); `recordStartRequest(subject, body, origin, { plan })` renders the statement with
424
+ the SAME `consumerCopyHelper.startContextOf(plan)` and the plan's short name the application passes (default: its
425
+ localized title), stores it verbatim with its `context`, and the start mail repeats it with
426
+ `email.start.rule` of that variant (the record's `context`). Usable `startRequestTtlSeconds`
427
+ (3600); the purchase takes it as `servicesStartedAt`/`consentedAt`.
428
+ - **Withdrawal** (`withdraw(subject | null, body, origin)`, managed only): in-app by `purchaseId`,
429
+ public by contract reference or invoice number plus an e-mail of the purchase, its profile or
430
+ its paygate customer. The declaration and the conditional `withdrawnAt` are written BEFORE
431
+ Stripe; the receipt is mailed at once; then the paygate steps under
432
+ `withdrawal:<id>:<step>` keys; then `onWithdrawal`. The refund comes from the application's
433
+ `UsageMeter` through the `@owlmeans/payment` calculators (deduction `usedAfter + settled +
434
+ clawed`); no meter, or `automaticRefunds` off, is `review` (no paygate call). A late
435
+ declaration is `expired` — recorded and acknowledged, nothing executed. A repeated one answers
436
+ the original receipt. The public answer is always the bare `DeclarationReceipt`.
437
+ - **Cancellation** (`cancel(subject | null, body, origin)`): in-app the organization's entitling
438
+ Stripe subscription; public a contract reference plus e-mail, else the one organization whose
439
+ paygate customer has that e-mail. Ordinary → `cancel_at_period_end`, or `cancel_at` a later
440
+ boundary (`cancellationEffectiveAt`, no proration); already scheduled → `already-scheduled`;
441
+ **extraordinary → `review`, the paygate untouched** (an operator decides, the receipt says so).
442
+ - **Observers `onConsent` / `onWithdrawal` / `onCancellation` run AFTER the records and the paygate
443
+ steps; a throw is recorded (`observers` event) and retried by `reconcile()` — unlike the paygate
444
+ callbacks, whose throw makes Stripe redeliver.** A `WithdrawalEvent` with `status: 'refunded'`
445
+ carries `units.returned` — take exactly those back; `review` means an operator refunds later,
446
+ and that refund arrives as an ordinary `RefundEvent`.
447
+ - **`RefundEvent.withdrawalId`**: a refund this package made for a withdrawal carries
448
+ `metadata.withdrawalId`; an `onRefund` observer MUST skip its own claw-back for it, or the units
449
+ are taken back twice.
69
450
 
70
- `paymentGate` is an immutable protocol tree. `paymentGateEntrypoints` binds its base, webhook, and
71
- resync declarations directly with `bind(protocol, handler)`; do not publish a flattened
72
- `paymentGateProtocols` compatibility list. The webhook is public because Stripe
73
- signature verification requires the untouched raw body, while resync carries the ED25519 guard.
74
- Never put an application auth guard on the Stripe webhook.
451
+ ## Durable-medium mails
75
452
 
76
- `appendPaymentGatewayService` also registers `ENTITLEMENT_GATE`. Paid capabilities belong on shared
77
- route declarations through `entitled(...)`, not in handlers. The gate fails closed when the
78
- subscription store cannot be read.
453
+ Sent through the optional mailer (`mail.alias`, default `MAILER_SERVICE`), text + HTML, in the
454
+ language the consumer was shown, from the `payment-consumer-rights` copy (`email.*`): purchase
455
+ confirmation (in-scope purchases with an e-mail; withdrawal information with the function's
456
+ address and the model form), consent confirmation, start confirmation, withdrawal receipt,
457
+ cancellation receipt. User values are HTML-escaped; a deadline is shown as its last included day.
458
+ The mails and the withdrawal information name the trader's `legalName, address, email`; the
459
+ statements its `name`. Every send, skip or failure is a `mail` event (step = kind); addresses on
460
+ `.test`/`.example`/`.invalid`/`.localhost` and every subdomain of them (`consumerFormatHelper.isReservedAddress`; case, a
461
+ display-name form and a trailing dot read through) are never sent (recorded as skipped); each `bcc`
462
+ address gets its own copy. **The purchase confirmation goes out once per purchase**: a delivery
463
+ sends it only after winning the conditional `confirmationMailAt` claim on the purchase row (a mail
464
+ event of it from before the claim counts too) — concurrent deliveries in several processes, a
465
+ redelivery and a subscription checkout refining its purchase mail nothing twice; a failed send is
466
+ retried by `reconcile` only. `useMailRenderer((kind, data, rendered) => message | null |
467
+ undefined)` replaces (`message`), suppresses (`null`, recorded as skipped) or keeps a mail. The
468
+ boot warns once when a mailing mechanism is on and the trader has no address or e-mail, or no
469
+ mailer is registered.
470
+
471
+ ## Reconcile
472
+
473
+ `paymentAccessOf(ctx).consumerRights().reconcile({ since?, limit? })` — the application's nightly job: retries the
474
+ paygate steps of withdrawals (refund, credit note, subscription cancel) and scheduled
475
+ cancellations, failed mails and failed observers; backfills purchases (records only, no mail) from
476
+ completed sessions of the last 16 days without a row; locks organizations that paid before the
477
+ lock from their paygate customer (never one an operator unlocked). A retry uses a fresh idempotency key (`…:<attempt>`; Stripe
478
+ replays a stored failure for a day) and first adopts a refund or credit note an earlier attempt
479
+ made (found by `metadata.withdrawalId`). Five failures of a step leave it to an operator. At most
480
+ `limit` (50) items per step.
481
+
482
+ ## Protocols, handlers and security
483
+
484
+ - `paymentGate` (bound by `paymentGateEntrypoints`): `webhook` is public because Stripe signs the
485
+ untouched raw body — never put an application guard on it; `resync` and `resyncSubscriptions`
486
+ carry `GUARD_ED25519`.
487
+ - **An application that declares the gate itself** — its own aliases, every route pinned to the
488
+ service that receives the webhook — binds its declarations to `paymentGateHandlers` (`webhook`,
489
+ `resync`, `resyncSubscriptions`) with `bind(own.webhook, paymentGateHandlers.webhook)` from
490
+ `@owlmeans/server-entrypoint` / `@owlmeans/server-app`, and never registers `paymentGate` or
491
+ `paymentGateEntrypoints`. A handler reads its context from the entrypoint it is bound to, so the
492
+ application's declaration is the one mounted and run. Its declarations keep the library's paths
493
+ (`webhookOf(ctx).webhookUrlOf` forms the Stripe URL from `paymentGate`'s), contracts (`PaygateParams`,
494
+ `ResyncResult`, `ResyncSubscriptionsResult` — `bind` refuses another shape at compile time) and
495
+ guards. Two ways to get it wrong: `bindAll(declarations, [paymentGateHandlers.webhook])` pairs by
496
+ object identity and leaves the application's declaration without a handler, and
497
+ `handlers().params(own.webhook, paymentGateHandlers.webhook)` answers every request with
498
+ `HandlerMisconfiguredError` (a handler bound to another protocol).
499
+ - `consumerRightsEntrypoints(protocols, { resolveEntity?, subjectOf?, guardMoney?, throttle?,
500
+ metaOf?, publicMinMs?, planNameOf?, serviceAlias? })` binds `makeConsumerRightsProtocols`' tree.
501
+ **Every hook gets the request's context as its LAST argument** — `resolveEntity(req, ctx)`,
502
+ `subjectOf(req, ctx)`, `guardMoney(req, action, ctx)`, `throttle(req, key, ctx)`,
503
+ `metaOf(req, ctx)`, `planNameOf(planSku, language, req, ctx)` — so an application reaches its
504
+ services (a throttle store) through it and keeps no module state. Account routes act for
505
+ `resolveEntity` (default `req.entity.id`, else `AuthForbidden`); consent, start, withdraw and
506
+ cancel pass `guardMoney` first (refuse API keys there). **A tree with a `public` subtree needs
507
+ `throttle` — a wiring error otherwise.** Public declarations are throttled with `{action, email,
508
+ ip}`, a filled `honeypot` gets a decoy receipt and nothing is recorded, and every answer takes at
509
+ least `publicMinMs` (1000 ms) so a match is not visible in the timing either.
510
+ - `checkoutReadEntrypoints(protocols, { resolveEntity?, gatewayAlias? })` binds
511
+ `makeCheckoutReadProtocols`: `amountPolicy` and `planPrices`; its `resolveEntity(req, ctx)` too.
512
+ - **`originHelper.requestOriginOf(req)`** is the evidence of every consumer act (the default `metaOf`): `ip` =
513
+ `cf-connecting-ip` → the LAST `x-forwarded-for` entry → `x-real-ip` → the socket; the raw
514
+ `x-forwarded-for`, `user-agent` (≤ 512), `cf-ipcountry`, `accept-language`.
515
+
516
+ ## Stripe self-management
517
+
518
+ Runs in `initialize()` of a managed gateway with `bootstrap` (default), after the context is
519
+ ready, and on a forced `stripeBootstrapOf(ctx).bootstrapStripe` from any managed process; each step independent: products
520
+ and prices (above), the portal configuration, the webhook endpoint. A deployment's identity is its
521
+ webhook URL (`webhookOf(ctx).webhookUrlOf()`: the `webhookService` alias's host and base); its rows carry the
522
+ `owner`.
523
+
524
+ - **The portal configuration**: customer update (tax id; email unless `stripe.lockCustomerEmail`;
525
+ address unless `mechanisms.countryLock` or `stripe.lockCustomerCountry`), invoice history,
526
+ payment method update, cancellation at period end without proration, price switching between the
527
+ active recurring prices. Its fingerprint covers the catalogue (incl. `currencyPrices`), the lock
528
+ flags, the region currencies, the branding and the deployment key. Each deployment owns its own configuration, tagged `{ owlmeans: 'payment',
529
+ service: <owner>, deployment: webhookOf(ctx).webhookUrlOf() }`; one tagged for another deployment (a former
530
+ webhook URL included) is never touched — a moved URL creates a new configuration.
531
+ - `portalLink(ctx, entityId, { flow, planSku?, returnUrl })`: a customer is required
532
+ (`PortalUnavailable`, 409); `Cancel`/`Update`/`Change` need an entitling Stripe subscription.
533
+ - **The webhook endpoint** at `webhookOf(ctx).webhookUrlOf()`, subscribed to `WEBHOOK_EVENTS`, on the API version
534
+ read back from the client; only an https public host. A deployment deletes only the endpoints its
535
+ own rows name. A new URL (a moved host, a new `webhookService`) creates the endpoint there, then
536
+ deletes the endpoints of the owner's rows at other URLs and those rows — no migration step. The
537
+ secret (create-only) is stored field-encrypted where the database has a key; the receiver reads
538
+ the newest row of its `owner`.
539
+ - **Do not bump the Stripe SDK** (17.x, API `2025-02-24.acacia`): `current_period_*`,
540
+ `invoice.subscription`, `invoice.payment_intent`, `charge.invoice` are top-level there and move
541
+ later; credit notes link a refund by `refund`; `presentment_details` is untyped. Read them through
542
+ narrow accessors.
543
+ - **Dashboard prerequisites** (test and live): a terms-of-service URL in Settings → Public details
544
+ before `checkoutTerms` is on (without it every checkout falls back to no checkbox — payments go on,
545
+ but the acceptance is not collected: watch for `checkout-terms-fallback` events); Checkout's return/refund
546
+ policy off or pointing at the Billing Terms, never "no refunds"; business name, address and
547
+ support e-mail in Public details; the "successful payments" and "refunds" customer e-mails.
548
+
549
+ ## Event dispatch
550
+
551
+ | Event | Persisted | Observer · event key |
552
+ |---|---|---|
553
+ | `customer.created` / `.updated` | customer upsert (`country`, `currency`) | — |
554
+ | `customer.deleted` | customer `deletedAt` | — |
555
+ | `checkout.session.completed` / `.async_payment_succeeded`, `payment` mode, paid | lock + purchase + confirmation mail, fulfillment (+ evidence), `fulfilledAt` after observers | `onTopUp` · session id; plugins `settled('paid')` |
556
+ | same, `subscription` mode | subscription applied if no webhook did (purchase in its first commit), purchase refined, lock, subscription evidence, confirmation mail | plugins `settled('paid')` |
557
+ | `checkout.session.async_payment_failed` | fulfillment `failedAt` | `onPaymentFailed {kind:'checkout'}` · `payment-failed:<session>:0`; `settled('failed')` |
558
+ | `checkout.session.expired` | unfulfilled fulfillment purged | plugins `settled('expired')` |
559
+ | `customer.subscription.created` / `.updated` / `.pending_update_*` / `.paused` / `.resumed` | subscription applied (+ `currency`) | `onSubscription` · classified |
560
+ | `customer.subscription.deleted` | applied as Canceled + `endedAt` | `canceled` |
561
+ | `customer.subscription.trial_will_end` | applied | `trial-ending` |
562
+ | `invoice.paid` | cycle invoice ⇒ re-read, applied as a renewal; otherwise `latestInvoiceId` | `renewed` |
563
+ | `invoice.payment_failed` / `.payment_action_required` | re-read and applied | classified, then `onPaymentFailed {kind:'invoice'}` · `payment-failed:<invoice>:<attempt>` |
564
+ | `invoice.upcoming` | nothing | — |
565
+ | `invoice.marked_uncollectible` / `invoice.voided` | re-read and applied / `latestInvoiceId` | classified / — |
566
+ | `charge.refunded`, `refund.created` / `.updated` (succeeded) | fulfillment `refundedMinor`/`refundedAt`; purchase `refundedMinor`, `refundedAt` on a whole refund | `onRefund` · `refund:<refund>` (`metadata`, `withdrawalId`) |
567
+ | `refund.failed` | — | — |
568
+ | `charge.dispute.*` | target `disputedAt`, `disputeStatus` | `onDispute {phase}` · `dispute:<dispute>:<phase>` |
569
+
570
+ A refund or dispute resolves to its target by payment intent (fulfillment), by charge, by invoice
571
+ (the subscription whose latest invoice it is, else the invoice's subscription); a subscription
572
+ refund touches the purchase only when it is of the purchase's own (first) invoice.
573
+
574
+ ## Observer API and idempotency keys
575
+
576
+ | Callback | Payload | Key | A throw |
577
+ |---|---|---|---|
578
+ | `onTopUp` | `TopUpCompletion` | session id | Stripe redelivers |
579
+ | `onSubscription` | `SubscriptionEvent` | `subscription:<id>:<change>:…` | Stripe redelivers |
580
+ | `onRefund` | `RefundEvent` (+ `metadata`, `withdrawalId`) | `refund:<refund>` | Stripe redelivers |
581
+ | `onDispute` | `DisputeEvent` | `dispute:<dispute>:<phase>` | Stripe redelivers |
582
+ | `onPaymentFailed` | `PaymentFailedEvent` | `payment-failed:<session\|invoice>:<attempt>` | Stripe redelivers |
583
+ | `onConsent` | `ConsentEvent` (`kind`, `consentId`, `purchaseIds`, `planSku`) | `consent:<id>` | recorded; `reconcile` retries |
584
+ | `onWithdrawal` | `WithdrawalEvent` (`status`, `purchase: PurchaseRef`, `refund`, `units`, `subscriptionCanceled`) | `withdrawal:<id>` | recorded; `reconcile` retries |
585
+ | `onCancellation` | `CancellationEvent` (`matched`, `kind`, `status`, `effectiveAt`) | `cancellation:<id>` | recorded; `reconcile` retries |
586
+
587
+ Every callback must be idempotent by its key. A proportional claw-back of an ordinary top-up
588
+ refund uses `netAmountMinor * refundedTotalMinor / paidMinor`.
589
+
590
+ ## Testing
591
+
592
+ Unit specs run a real server context — real catalogue, services and gates — over in-memory
593
+ resources (unique and sparse-unique indexes, raw conditional updates) and a fake Stripe that records
594
+ every SDK call and its request options (idempotency keys) and can fail a method's next calls
595
+ (`state.failures`: a message, a real SDK error such as `new Stripe.errors.StripeInvalidRequestError(…)`,
596
+ or a list of them, one per call), so "no Stripe call" is an assertion. `makeFakeContext` wires the
597
+ consumer-rights call before the gateway by default (`gatewayFirst`, `rights` and a pre-init `wire`
598
+ hook test the other orders); `gateway` passes the gateway's options (default `{ manage: false }`,
599
+ the fake always its Stripe client, so a managed one boot-bootstraps against it), `service` /
600
+ `host` / `base` / `services` shape `cfg.service` and `cfg.services`, and `seed` pre-fills stores
601
+ (a database shared between two processes). `gate-handlers.spec.ts` binds `paymentGateHandlers`
602
+ onto a re-declared, pinned gate and runs it in that process's context. The consumer-rights service there is
603
+ managed through the fake (`appendConsumerRights({ manage: true, stripe })`) with a console mailer
604
+ (`fake.mails`). The Mongo-gated specs prove admission under concurrency, the collection validators
605
+ of every record, the unique indexes, the concurrent first lock and the single winner of
606
+ concurrent withdrawals.
79
607
 
80
608
  ## External docs
81
609
 
82
- - https://docs.stripe.com/api/checkout/sessions/create — Checkout accepts inline `price_data` with integer minor-unit `unit_amount`; automatic tax is enabled on the Session and amount items are tax-exclusive.
83
- - https://docs.stripe.com/checkout/fulfillment — Fulfillment must be idempotent, check payment state and support delayed-payment success events rather than trusting completion alone.
610
+ - https://docs.stripe.com/api/checkout/sessions/create — `customer`: "If the Customer already has a valid email set, the email will be prefilled and not editable in Checkout" (else Checkout saves the typed one); `customer_email` only prefills a NEW customer and cannot be combined with `customer`. Inline `price_data`; `consent_collection.terms_of_service` needs a terms URL in the Dashboard (else `invalid_request_error` on param `consent_collection[terms_of_service]`); `custom_text.{submit, after_submit, terms_of_service_acceptance}` ≤ 1200 characters each; `currency` forces a Price's currency option; `expires_at` 30 min – 24 h.
611
+ - https://docs.stripe.com/tax/customer-locations — minimal tax location: country alone except US (postal code), CA and IN (postal code or province); https://docs.stripe.com/tax/checkout/page — an existing customer with `customer_update.address: 'never'` is taxed on its saved address. Verified against test mode (2026-10): a pinned DE customer keeps its VAT when the card country is switched to US; a country-only US/CA customer is refused at session creation.
612
+ - https://docs.stripe.com/payments/checkout/localize-prices/manual-currency-prices — `currency_options` on a Price, one reusable Price for several currencies; manual options override Adaptive Pricing for that currency.
613
+ - https://docs.stripe.com/payments/currencies/localize-prices/adaptive-pricing — Adaptive Pricing requires the price currency to be a settlement currency; webhook amounts stay in the integration currency.
614
+ - https://docs.stripe.com/api/checkout/sessions/create?query=adaptive_pricing — `adaptive_pricing.enabled` defaults to the Dashboard setting when omitted; send an explicit boolean for every session.
615
+ - https://docs.stripe.com/payments/klarna — Klarna eligibility depends on currency, customer location and purchase use case; verify the account's supported currencies before explicitly requesting it.
616
+ - https://docs.stripe.com/invoicing/multi-currency-customers — a customer's subscriptions share one currency; one-time payments may differ.
617
+ - https://docs.stripe.com/invoicing/integration/programmatic-credit-notes — preview a credit note on an invoice line; link an existing refund with `refund`; custom lines are not allowed with automatic tax.
618
+ - https://docs.stripe.com/tax/reports — a refund or a credit note lowers reported tax; only the credit note is the corrective document of an issued invoice.
619
+ - https://docs.stripe.com/api/refunds/create — `payment_intent`, `amount`, `reason: requested_by_customer`, `metadata`; an idempotency key replays the stored answer (failures too) for 24 h.
620
+ - https://docs.stripe.com/api/subscriptions/cancel and /update — `cancel(prorate, invoice_now, cancellation_details)`; `update(cancel_at_period_end | cancel_at, proration_behavior)`.
621
+ - https://docs.stripe.com/payments/checkout/receipts — one-time Checkout needs `invoice_creation.enabled` for a post-payment invoice; a Customer's `preferred_locales` localizes Stripe mails.
622
+ - https://docs.stripe.com/checkout/fulfillment — fulfillment must be idempotent and support delayed-payment success events.
623
+ - https://docs.stripe.com/api/webhook_endpoints/create — the signing `secret` is returned only by create; `api_version` is create-only.
624
+ - https://docs.stripe.com/api/customer_portal/configurations/create — `features.customer_update.allowed_updates`, subscription cancel/update features; configurations are never deletable.
625
+ - https://docs.stripe.com/api/tax/calculations/create — `percentage_decimal` is a STRING; parse it exactly.
626
+ - https://docs.stripe.com/api/fx_quotes/create — a PREVIEW endpoint (`stripe.rawRequest`); `reference_rate` for settlement conversion.
627
+ - https://docs.stripe.com/currencies/localize-prices/fx-quotes-api — `exchange_rate` is fee-inclusive (`base_rate × (1 − fx_fee_rate)`, 2%); dividing a price by `base_rate` is the fee-free local price.
628
+ - https://docs.stripe.com/payments/currencies/localize-prices/adaptive-pricing — the buyer pays a 2–4% conversion fee that Stripe decides ("includes 4% conversion fee" on a PLN Checkout, 2026-10): the mid-market rate × (1 + fee), a different fee from the FX Quotes' `fx_fee_rate`.
629
+
630
+ ## Related
631
+
632
+ - [[entitlements]] — the model across packages
633
+ - [[payment]] — the contracts: grammars, views, consumer-rights calculators, copy, refusals, factories
634
+ - [[web-payment]] — hooks and pieces, the consumer-rights dialogs and functions
635
+ - [[mailer]] — the mail transport the consumer-rights mails go through
636
+ - [[mongo-resource]] — raw collection access, duplicate-key detection, field locking
637
+
638
+ ## Parts
639
+
640
+ | Part | Load it when |
641
+ |---|---|
642
+ | [reference](parts/reference.md) | implementing or changing consumer rights — the policy, records, service methods, withdrawal, cancellation, mails or handler options |