@jskit-ai/payments-core 0.2.36 → 0.2.38

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.
package/locales/en.json CHANGED
@@ -18,7 +18,13 @@
18
18
  "payment_insufficient_credits": "Not enough credits for this action.",
19
19
  "payment_debit_missing": "No debit exists for this reference.",
20
20
  "payment_customer_unbound": "Bind this provider customer before processing its events.",
21
- "payment_sandbox_only": "Only production takes real payments: use the sandbox payment environment."
21
+ "payment_sandbox_only": "Only production takes real payments: use the sandbox payment environment.",
22
+ "payment_live_key_refused": "A live Stripe key takes real payments, and only APP_ENV=production takes them: use a test key (sk_test_ or rk_test_) in this environment.",
23
+ "payment_stand_in_refused": "A stand-in for Stripe's API works only in development and tests: remove apiBaseUrl in this environment.",
24
+ "payment_top_ups_unavailable": "This application takes no top-ups.",
25
+ "payment_top_up_amount_invalid": "Choose a top-up amount within this application's limits, in the currency's smallest unit.",
26
+ "payment_top_up_missing": "This account has no such top-up.",
27
+ "payment_provider_unavailable": "The payment provider did not answer. Try again: repeating this request is safe."
22
28
  },
23
29
  "payments": {
24
30
  "scope": {
@@ -37,18 +43,22 @@
37
43
  "recoveryObjectId": "Supply the exact provider object ID to recover.",
38
44
  "reference": "Use a nonempty business reference of at most 150 characters.",
39
45
  "creditQuantity": "Use a positive integer credit quantity, at most one billion.",
40
- "timestamp": "Use an integer UTC timestamp in milliseconds."
46
+ "timestamp": "Use an integer UTC timestamp in milliseconds.",
47
+ "topUpDescription": "Describe the top-up in at most 500 characters, or leave the description out."
41
48
  },
42
49
  "reference": {
43
50
  "otherPlan": "The checkout request already selected another plan.",
44
- "differentInputs": "This business reference was already used with different inputs."
51
+ "differentInputs": "This business reference was already used with different inputs.",
52
+ "otherAmount": "The top-up request already chose another amount."
45
53
  },
46
54
  "provider": {
47
55
  "checkAccount": "Check the {provider} account, price mapping and subscription shape.",
48
56
  "unsupportedEvent": "The event is not a supported subscription payment for this customer.",
49
57
  "objectIdMissing": "The provider did not return an object ID.",
50
58
  "subscriptionBinding": "Check the provider subscription and logical price binding.",
51
- "renewalBinding": "Check the renewal's logical price binding."
59
+ "renewalBinding": "Check the renewal's logical price binding.",
60
+ "topUpSession": "Check the Stripe account and the top-up's Checkout session.",
61
+ "topUpAmount": "The amount paid differs from the top-up's amount, so it was not credited."
52
62
  },
53
63
  "webhook": {
54
64
  "rawBodyRequired": "Supply the unmodified webhook request bytes.",
@@ -60,7 +70,9 @@
60
70
  "sharedConnectionRequired": "Select a shared Stripe or Paddle connection with a backend API-key Env reference for {environment}.",
61
71
  "paddleEnvironment": "Select a Paddle connection configured for {environment}.",
62
72
  "paddleTaxCategory": "Choose the Paddle tax category for the products this app sells.",
63
- "paddleClientToken": "Set the Env reference for this environment's Paddle public client token."
73
+ "paddleClientToken": "Set the Env reference for this environment's Paddle public client token.",
74
+ "paddleTopUps": "Top-ups take Stripe Checkout payments: select a Stripe connection for {environment}, or remove topUps.",
75
+ "topUpRange": "Make the largest top-up at least the smallest."
64
76
  },
65
77
  "catalogue": {
66
78
  "reviewFirst": "Review the current catalogue and resolve provider drift or unfinished requests first.",
@@ -0,0 +1,28 @@
1
+ const TOP_UPS_TABLE = "payment_top_ups";
2
+
3
+ // One prepaid top-up: the merchant's and top-up's key, and its state as JSON (its billable subject, amount, status
4
+ // and Checkout session), written before the provider hears of it.
5
+ async function createTopUps(knex) {
6
+ if (!(await knex.schema.hasTable(TOP_UPS_TABLE))) {
7
+ await knex.schema.createTable(TOP_UPS_TABLE, (table) => {
8
+ table.string("top_up_key", 64).primary();
9
+ table.text("payload", "mediumtext").notNullable();
10
+ });
11
+ }
12
+ }
13
+
14
+ exports.up = async function up(knex) {
15
+ // On MySQL and MariaDB the table takes the collation of the payment tables already there.
16
+ const { migrateInExistingCollation } = await import("@jskit-ai/database-runtime/server/tableCollationMigrations");
17
+ await migrateInExistingCollation(knex, {
18
+ migration: "payments_core_top_ups.cjs",
19
+ up: createTopUps,
20
+ tables: [TOP_UPS_TABLE],
21
+ referenceTables: ["payment_accounts"]
22
+ });
23
+ await createTopUps(knex);
24
+ };
25
+
26
+ exports.down = async function down(knex) {
27
+ await knex.schema.dropTableIfExists(TOP_UPS_TABLE);
28
+ };
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@jskit-ai/payments-core",
3
- "version": "0.2.36",
3
+ "version": "0.2.38",
4
4
  "type": "module",
5
- "description": "Application-owned payment configuration, subscription access and transactional usage credits.",
5
+ "description": "Application-owned payment configuration, subscription access, prepaid top-ups and transactional usage credits.",
6
6
  "exports": {
7
7
  "./shared": "./src/shared/configuration.js",
8
+ "./shared/topUps": "./src/shared/topUps.js",
8
9
  "./configuration.schema.json": "./contracts/configuration.schema.json",
9
10
  "./conformance.json": "./contracts/conformance.json",
10
11
  "./docs/contract.md": "./docs/contract.md",
@@ -23,7 +24,7 @@
23
24
  "test": "jskit test"
24
25
  },
25
26
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.222",
27
+ "@jskit-ai/resource-core": "0.1.223",
27
28
  "@paddle/paddle-node-sdk": "3.10.0",
28
29
  "ajv": "8.20.0",
29
30
  "stripe": "22.6.2"
@@ -50,6 +51,9 @@
50
51
  },
51
52
  {
52
53
  "tableName": "payment_catalogues"
54
+ },
55
+ {
56
+ "tableName": "payment_top_ups"
53
57
  }
54
58
  ]
55
59
  }
@@ -69,9 +73,9 @@
69
73
  }
70
74
  },
71
75
  "peerDependencies": {
72
- "@jskit-ai/database-runtime": "0.1.281",
73
- "@jskit-ai/kernel": "0.2.31",
74
- "@jskit-ai/resource-runtime": "0.2.45"
76
+ "@jskit-ai/database-runtime": "0.1.282",
77
+ "@jskit-ai/kernel": "0.2.32",
78
+ "@jskit-ai/resource-runtime": "0.2.46"
75
79
  },
76
80
  "peerDependenciesMeta": {
77
81
  "@jskit-ai/database-runtime": {
@@ -1,6 +1,22 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { APP_ENVIRONMENTS } from "@jskit-ai/kernel/shared/support/appEnvironment";
3
3
  import { PaymentError, fingerprint } from "./errors.js";
4
+ import { SETTLED_TOP_UP, checkTopUpAmount, composedTopUps, nextTopUpStatus, topUpReturnUrl, topUpView } from "./topUps.js";
5
+
6
+ const REQUEST_ID = /^[A-Za-z0-9_-]{1,100}$/;
7
+ const TOP_UP_ID = /^[0-9a-f]{64}$/u;
8
+
9
+ function checkRequestId(requestId) {
10
+ if (typeof requestId !== "string" || !REQUEST_ID.test(requestId)) throw new PaymentError("payment_request_invalid", "Supply a stable checkout request identifier.");
11
+ }
12
+ function checkBillingEmail(email) {
13
+ if (typeof email !== "string" || email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new PaymentError("payment_input_invalid", "Supply the authenticated billing contact's email.", 422, { messageCode: "payments.input.billingEmail" });
14
+ }
15
+ // A provider failure is shown as one safe sentence; the provider's own error stays the cause, for the application's log.
16
+ function providerUnavailable(error) {
17
+ if (error instanceof PaymentError) return error;
18
+ return new PaymentError("payment_provider_unavailable", "The payment provider did not answer. Try again: repeating this request is safe.", 502, { cause: error });
19
+ }
4
20
 
5
21
  /**
6
22
  * Application composition boundary: authorization is mandatory and supplied by
@@ -13,10 +29,13 @@ import { PaymentError, fingerprint } from "./errors.js";
13
29
  * @param {string} dependencies.returnUrl
14
30
  * @param {(actor: unknown, request: { subjectId: string, action: string }) => boolean | Promise<boolean>} dependencies.authorize
15
31
  * @param {"development" | "test" | "staging" | "production"} dependencies.appEnv The application's APP_ENV
16
- * (`appEnvironment(env)`). Only production takes real money: elsewhere checkout and billing changes in the live
17
- * payment environment are refused; the sandbox environment works everywhere.
32
+ * (`appEnvironment(env)`). Only production takes real money: elsewhere checkout, top-ups and billing changes in the
33
+ * live payment environment are refused; the sandbox environment works everywhere.
34
+ * @param {import("./types.js").PaymentTopUps} [dependencies.topUps] Prepaid top-ups: the validated configuration's
35
+ * `topUps` as `offer`, and `credit`, the application's function that adds a paid top-up to its own balance.
36
+ * @param {() => number} [dependencies.clock]
18
37
  */
19
- function createPaymentCheckoutService({ adapter, store, payments, merchantScope, returnUrl, authorize, appEnv }) {
38
+ function createPaymentCheckoutService({ adapter, store, payments, merchantScope, returnUrl, authorize, appEnv, topUps, clock = Date.now }) {
20
39
  // readable-check: allow method-probe - input validation: the application passes its billable-subject authorization
21
40
  if (typeof authorize !== "function") throw new TypeError("Supply the application's billable-subject authorization function.");
22
41
  if (!APP_ENVIRONMENTS.includes(appEnv)) throw new TypeError("Supply appEnv, the application's APP_ENV: appEnvironment(env).");
@@ -25,6 +44,7 @@ function createPaymentCheckoutService({ adapter, store, payments, merchantScope,
25
44
  throw new TypeError("Configure an HTTPS application return/checkout URL (HTTP is allowed only for local development).");
26
45
  }
27
46
  const merchant = structuredClone(merchantScope);
47
+ const prepaid = composedTopUps(topUps, adapter, store);
28
48
  // Before any provider write: outside production nothing creates a live customer, checkout or billing session.
29
49
  function requireRealMoneyAllowed() {
30
50
  if (merchant.environment === "live" && appEnv !== "production") {
@@ -63,8 +83,8 @@ function createPaymentCheckoutService({ adapter, store, payments, merchantScope,
63
83
  const scope = await allowed(actor, subjectId, "checkout");
64
84
  requireRealMoneyAllowed();
65
85
  adapter.validatePlan(planId);
66
- if (typeof requestId !== "string" || !/^[A-Za-z0-9_-]{1,100}$/.test(requestId)) throw new PaymentError("payment_request_invalid", "Supply a stable checkout request identifier.");
67
- if (typeof email !== "string" || email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new PaymentError("payment_input_invalid", "Supply the authenticated billing contact's email.", 422, { messageCode: "payments.input.billingEmail" });
86
+ checkRequestId(requestId);
87
+ checkBillingEmail(email);
68
88
  const identity = fingerprint(scope);
69
89
  const customerId = await perform(scope, async (tx) => tx.state.customerId
70
90
  ? { cached: true, result: tx.state.customerId }
@@ -138,8 +158,92 @@ function createPaymentCheckoutService({ adapter, store, payments, merchantScope,
138
158
  return { pending: false, result };
139
159
  });
140
160
  }
161
+ function requireTopUps() {
162
+ if (!prepaid) throw new PaymentError("payment_top_ups_unavailable", "This application takes no top-ups.", 409);
163
+ return prepaid;
164
+ }
165
+ // Starts a top-up: writes it down for the authorized subject, then opens a one-off Checkout payment for it. The
166
+ // same request id answers the same top-up and Checkout page; a failed provider request leaves it starting, and
167
+ // repeating the request asks the provider again under the same idempotency key.
168
+ async function topUp({ actor, subjectId, amount, requestId, email = null, description = null }) {
169
+ await allowed(actor, subjectId, "topUp");
170
+ const { offer } = requireTopUps();
171
+ requireRealMoneyAllowed();
172
+ checkRequestId(requestId);
173
+ checkTopUpAmount(offer, amount);
174
+ if (email !== null) checkBillingEmail(email);
175
+ if (description !== null && (typeof description !== "string" || !description || description.length > 500)) {
176
+ throw new PaymentError("payment_input_invalid", "Describe the top-up in at most 500 characters, or leave the description out.", 422, { messageCode: "payments.input.topUpDescription" });
177
+ }
178
+ const id = fingerprint([merchant.applicationId, merchant.integrationId, merchant.providerAccountId, merchant.environment, subjectId, requestId]);
179
+ const saved = await store.createTopUp(merchant, {
180
+ id, subjectId, requestId, amount, currency: offer.currency, status: "starting", sessionId: null, url: null, paymentIntentId: null, createdAt: clock(), settledAt: null
181
+ });
182
+ if (saved.amount !== amount || saved.currency !== offer.currency) {
183
+ throw new PaymentError("payment_reference_conflict", "The top-up request already chose another amount.", 409, { messageCode: "payments.reference.otherAmount" });
184
+ }
185
+ if (saved.status !== "starting") return topUpView(saved);
186
+ let page;
187
+ try {
188
+ page = await adapter.createTopUpCheckout({
189
+ topUpId: id, amount, currency: offer.currency, name: offer.name, description, email,
190
+ returnUrl: topUpReturnUrl(target.href, id), requestId: `top-up-${id}`
191
+ });
192
+ } catch (error) { throw providerUnavailable(error); }
193
+ return store.withTopUp(merchant, id, async (held) => {
194
+ if (held.topUp.status === "starting") Object.assign(held.topUp, { status: "open", sessionId: page.id, url: page.url });
195
+ return topUpView(held.topUp);
196
+ });
197
+ }
198
+ // The one path that settles a top-up, for its webhook and its return page alike. Under the top-up's row lock the
199
+ // provider's outcome moves its status on (nextTopUpStatus), and only the move to paid calls the application's
200
+ // credit, in the same transaction: a second report of the same payment, from either door, finds it paid and
201
+ // credits nothing, and a credit that fails rolls the move back, so the next report credits it. null: the facts
202
+ // are about no top-up of this merchant, or a Checkout session other than the one written down for it. Its callers,
203
+ // confirmTopUp and webhook, have found top-ups composed.
204
+ async function settle(facts) {
205
+ return store.withTopUp(merchant, facts.topUpId, async (held) => {
206
+ const saved = held.topUp;
207
+ if (!saved || (saved.sessionId ?? facts.sessionId) !== facts.sessionId) return null;
208
+ // A top-up still starting lost the provider's answer after its session was made: the session it names is its own.
209
+ saved.sessionId = facts.sessionId;
210
+ const status = nextTopUpStatus(saved.status === "starting" ? "open" : saved.status, facts.outcome);
211
+ const credited = status === "paid" && saved.status !== "paid";
212
+ if (credited) {
213
+ if (facts.amount !== saved.amount || facts.currency !== saved.currency) {
214
+ throw new PaymentError("payment_provider_result_invalid", "The amount paid differs from the top-up's amount, so it was not credited.", 502, { messageCode: "payments.provider.topUpAmount" });
215
+ }
216
+ await prepaid.credit({ reference: `top-up:${saved.id}`, subjectId: saved.subjectId, amount: saved.amount, currency: saved.currency }, held.options);
217
+ saved.paymentIntentId = facts.paymentIntentId;
218
+ }
219
+ if (status !== saved.status) Object.assign(saved, { status, settledAt: SETTLED_TOP_UP.includes(status) ? clock() : null });
220
+ return { ...topUpView(saved), credited };
221
+ });
222
+ }
223
+ // The application's return page asks: the server reads the top-up's Checkout session from the provider with its
224
+ // own key and settles it, so nothing the browser says counts as payment. A settled top-up answers without asking.
225
+ async function confirmTopUp({ actor, subjectId, topUpId }) {
226
+ await allowed(actor, subjectId, "topUp");
227
+ requireTopUps();
228
+ const saved = typeof topUpId === "string" && TOP_UP_ID.test(topUpId) ? await store.inspectTopUp(merchant, topUpId) : null;
229
+ if (saved?.subjectId !== subjectId) throw new PaymentError("payment_top_up_missing", "This account has no such top-up.", 404);
230
+ if (SETTLED_TOP_UP.includes(saved.status) || !saved.sessionId) return { ...topUpView(saved), credited: false };
231
+ let facts;
232
+ try { facts = await adapter.retrieveTopUpCheckout(saved.sessionId); }
233
+ catch (error) { throw providerUnavailable(error); }
234
+ if (facts.topUpId !== saved.id) throw new PaymentError("payment_provider_result_invalid", "Check the Stripe account and the top-up's Checkout session.", 502, { messageCode: "payments.provider.topUpSession" });
235
+ return settle(facts);
236
+ }
141
237
  async function webhook({ rawBody, signature }) {
142
238
  const event = await adapter.verifyEvent(rawBody, signature);
239
+ if (prepaid) {
240
+ // A Checkout session naming no top-up of this merchant, another system's on the same account say, is acknowledged and left.
241
+ const facts = adapter.topUpEvent(event);
242
+ if (facts) {
243
+ const settled = TOP_UP_ID.test(facts.topUpId) ? await settle(facts) : null;
244
+ return settled ?? { ignored: true };
245
+ }
246
+ }
143
247
  const identity = adapter.eventIdentity(event);
144
248
  if (!identity) return { ignored: true };
145
249
  const { eventId, customerId } = identity;
@@ -154,6 +258,8 @@ function createPaymentCheckoutService({ adapter, store, payments, merchantScope,
154
258
  history,
155
259
  checkout,
156
260
  portal,
261
+ topUp,
262
+ confirmTopUp,
157
263
  webhook,
158
264
  reconcilePending
159
265
  });
@@ -1,10 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
3
  // code is the stable payment_* code callers branch on; a code shared by several
4
- // sentences adds a messageCode (and messageParams) naming this sentence.
4
+ // sentences adds a messageCode (and messageParams) naming this sentence. `cause` keeps
5
+ // the provider's own failure, for the application's log, behind a sentence that is safe to show.
5
6
  class PaymentError extends Error {
6
- constructor(code, message, statusCode = 422, { messageCode = "", messageParams = {} } = {}) {
7
- super(message);
7
+ constructor(code, message, statusCode = 422, { messageCode = "", messageParams = {}, cause } = {}) {
8
+ super(message, cause === undefined ? undefined : { cause });
8
9
  this.name = "PaymentError";
9
10
  this.code = code;
10
11
  this.statusCode = statusCode;
@@ -59,8 +59,21 @@ const paymentCatalogueResource = defineTableResource({
59
59
  }
60
60
  });
61
61
 
62
+ // One prepaid top-up under one merchant, keyed by the merchant and the top-up: its state as JSON, holding the billable
63
+ // subject it was written down for, so a provider's event never names whose balance it credits.
64
+ const paymentTopUpResource = defineTableResource({
65
+ name: "paymentTopUps",
66
+ tableName: "payment_top_ups",
67
+ ownership: "public",
68
+ idProperty: "top_up_key",
69
+ schema: {
70
+ id: key("top_up_key"),
71
+ payload: text
72
+ }
73
+ });
74
+
62
75
  // The feature's owns entries: each key is an opaque fingerprint, not a numeric id.
63
- const PAYMENT_TABLES = Object.freeze([paymentAccountResource, paymentEntryResource, paymentCustomerResource, paymentCatalogueResource]
76
+ const PAYMENT_TABLES = Object.freeze([paymentAccountResource, paymentEntryResource, paymentCustomerResource, paymentCatalogueResource, paymentTopUpResource]
64
77
  .map((resource) => Object.freeze({ resource, normalizeId: normalizeOpaqueId })));
65
78
 
66
79
  export {
@@ -68,5 +81,6 @@ export {
68
81
  paymentAccountResource,
69
82
  paymentCatalogueResource,
70
83
  paymentCustomerResource,
71
- paymentEntryResource
84
+ paymentEntryResource,
85
+ paymentTopUpResource
72
86
  };
@@ -18,9 +18,10 @@ function identifier(value) {
18
18
  const accountKey = (scope) => fingerprint([...merchant(scope), identifier(scope.subjectId)]);
19
19
  const customerKey = (scope, customerId) => fingerprint([...merchant(scope), identifier(customerId)]);
20
20
  const entryKey = (account, reference) => fingerprint([account, identifier(reference)]);
21
+ const topUpKey = (scope, topUpId) => fingerprint([...merchant(scope), "top-up", identifier(topUpId)]);
21
22
 
22
23
  /**
23
- * The payment store on its table resources' handles: each account and each catalogue is one locked row holding its
24
+ * The payment store on its table resources' handles: each account, catalogue and top-up is one locked row holding its
24
25
  * state as JSON, an account's entries are recorded once per reference, and a provider customer is bound to one
25
26
  * subject per merchant. Every call works in a system context, because a row's scope is its key.
26
27
  * @param {object} dependencies
@@ -29,10 +30,11 @@ const entryKey = (account, reference) => fingerprint([account, identifier(refere
29
30
  * @returns {import("./types.js").PaymentStore}
30
31
  */
31
32
  function createPaymentStore({ resources, systemContext }) {
32
- const { paymentAccounts: accounts, paymentEntries: entries, paymentCustomers: customers, paymentCatalogues: catalogues } = resources;
33
+ const { paymentAccounts: accounts, paymentEntries: entries, paymentCustomers: customers, paymentCatalogues: catalogues, paymentTopUps: topUps } = resources;
33
34
  const accountOptions = Object.freeze({ context: systemContext("an account is read and changed by its merchant and subject key") });
34
35
  const customerOptions = Object.freeze({ context: systemContext("a provider customer is bound and resolved by its merchant and customer key") });
35
36
  const catalogueOptions = Object.freeze({ context: systemContext("a catalogue is read and changed by its merchant key") });
37
+ const topUpOptions = Object.freeze({ context: systemContext("a top-up is read and changed by its merchant and top-up key") });
36
38
 
37
39
  async function inspect(scope) {
38
40
  const account = await accounts.get(accountKey(scope), {}, { ...accountOptions, missing: "skip" });
@@ -91,13 +93,43 @@ function createPaymentStore({ resources, systemContext }) {
91
93
  });
92
94
  }
93
95
 
96
+ async function inspectTopUp(scope, topUpId) {
97
+ const topUp = await topUps.get(topUpKey(scope, topUpId), {}, { ...topUpOptions, missing: "skip" });
98
+ return topUp ? JSON.parse(topUp.payload) : null;
99
+ }
100
+
101
+ // Writes the top-up down unless one with its id is already there, and answers the one that is: a repeated request
102
+ // gets the first one's state.
103
+ async function createTopUp(scope, topUp) {
104
+ const saved = await topUps.findOrCreate({ id: topUpKey(scope, topUp?.id), payload: JSON.stringify(topUp) }, topUpOptions);
105
+ return JSON.parse(saved.payload);
106
+ }
107
+
108
+ // Runs work on the top-up locked, or on null when there is none (the lock creates nothing), and saves the state the
109
+ // work leaves. work also gets the options of the transaction the lock holds, for an application write that must
110
+ // commit with it or not at all: its handle calls take them and join that transaction.
111
+ async function withTopUp(scope, topUpId, work) {
112
+ const key = topUpKey(scope, topUpId);
113
+ return topUps.withTransaction(topUpOptions, async (txOptions) => {
114
+ const locked = await topUps.lock(key, { ...txOptions, missing: "skip" });
115
+ const topUp = locked ? JSON.parse(locked.payload) : null;
116
+ const result = await work({ topUp, options: txOptions });
117
+ const payload = topUp ? JSON.stringify(topUp) : null;
118
+ if (payload && payload !== locked.payload) await topUps.patch(key, { payload }, { ...txOptions, returning: "none" });
119
+ return result;
120
+ });
121
+ }
122
+
94
123
  return Object.freeze({
95
124
  inspect,
96
125
  withAccount,
97
126
  bindCustomer,
98
127
  resolveCustomer,
99
128
  inspectCatalogue,
100
- withCatalogue
129
+ withCatalogue,
130
+ inspectTopUp,
131
+ createTopUp,
132
+ withTopUp
101
133
  });
102
134
  }
103
135
 
@@ -1,4 +1,5 @@
1
1
  import Stripe from "stripe";
2
+ import { APP_ENVIRONMENTS } from "@jskit-ai/kernel/shared/support/appEnvironment";
2
3
  import { PaymentError } from "./errors.js";
3
4
  import { createPriceBindings } from "./priceBindings.js";
4
5
 
@@ -8,10 +9,59 @@ const invalid = () => {
8
9
  messageCode: "payments.provider.checkAccount", messageParams: { provider: "Stripe" }
9
10
  });
10
11
  };
12
+ const invalidTopUp = () => {
13
+ throw new PaymentError("payment_provider_result_invalid", "Check the Stripe account and the top-up's Checkout session.", 502, {
14
+ messageCode: "payments.provider.topUpSession"
15
+ });
16
+ };
17
+ // A live secret or restricted key takes real money; only APP_ENV=production uses one. Test keys work everywhere.
18
+ const LIVE_KEY = /^(?:sk|rk)_live_/u;
19
+ // The Checkout session events of a top-up: paid now or later (a bank payment), waiting for a bank payment, its bank
20
+ // payment failed, and its page closed unpaid.
21
+ const TOP_UP_EVENTS = Object.freeze([
22
+ "checkout.session.completed",
23
+ "checkout.session.async_payment_succeeded",
24
+ "checkout.session.async_payment_failed",
25
+ "checkout.session.expired"
26
+ ]);
27
+ // What a payment-mode Checkout session's status and payment status say of its top-up.
28
+ const SESSION_OUTCOMES = Object.freeze({
29
+ "open/unpaid": "open",
30
+ "complete/paid": "paid",
31
+ "complete/unpaid": "processing",
32
+ "expired/unpaid": "expired"
33
+ });
34
+
35
+ /**
36
+ * The Stripe SDK's settings: no automatic retries, and, given `apiBaseUrl`, requests to that stand-in for Stripe's
37
+ * API instead of Stripe, which only development and tests take, so a test never reaches Stripe.
38
+ * @param {string} appEnv
39
+ * @param {string} apiBaseUrl
40
+ */
41
+ function stripeClientSettings(appEnv, apiBaseUrl) {
42
+ if (!apiBaseUrl) return { maxNetworkRetries: 0 };
43
+ if (appEnv !== "development" && appEnv !== "test") {
44
+ throw new PaymentError("payment_stand_in_refused", "A stand-in for Stripe's API works only in development and tests: remove apiBaseUrl in this environment.", 409);
45
+ }
46
+ const url = new URL(apiBaseUrl);
47
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
48
+ throw new TypeError("Give apiBaseUrl as the stand-in's origin alone, such as http://127.0.0.1:12111.");
49
+ }
50
+ return {
51
+ maxNetworkRetries: 0,
52
+ protocol: url.protocol.slice(0, -1),
53
+ host: url.hostname,
54
+ port: Number(url.port) || (url.protocol === "https:" ? 443 : 80)
55
+ };
56
+ }
11
57
 
12
58
  /**
13
59
  * @param {object} options
14
60
  * @param {string} [options.apiKey]
61
+ * @param {"development" | "test" | "staging" | "production"} options.appEnv The application's APP_ENV
62
+ * (`appEnvironment(env)`). A live key (sk_live_, rk_live_) is refused unless it is production; test keys work in
63
+ * every environment.
64
+ * @param {string} [options.apiBaseUrl] A stand-in for Stripe's API (its origin), for development and tests only.
15
65
  * @param {string} options.webhookSecret
16
66
  * @param {"sandbox" | "live"} options.environment
17
67
  * @param {string} options.providerAccountId
@@ -20,7 +70,11 @@ const invalid = () => {
20
70
  * @param {import("stripe").Stripe} [options.client]
21
71
  */
22
72
  // readable-check: allow dependency-default - data: historicalPriceBindings maps retired price ids to plans, not a collaborator
23
- function createStripePaymentAdapter({ apiKey, webhookSecret, environment, providerAccountId, priceBindings, historicalPriceBindings = {}, client = new Stripe(apiKey, { maxNetworkRetries: 0 }) }) {
73
+ function createStripePaymentAdapter({ apiKey, appEnv, apiBaseUrl = "", webhookSecret, environment, providerAccountId, priceBindings, historicalPriceBindings = {}, client = new Stripe(apiKey, stripeClientSettings(appEnv, apiBaseUrl)) }) {
74
+ if (!APP_ENVIRONMENTS.includes(appEnv)) throw new TypeError("Supply appEnv, the application's APP_ENV: appEnvironment(env).");
75
+ if (LIVE_KEY.test(String(apiKey ?? "")) && appEnv !== "production") {
76
+ throw new PaymentError("payment_live_key_refused", "A live Stripe key takes real payments, and only APP_ENV=production takes them: use a test key (sk_test_ or rk_test_) in this environment.", 409);
77
+ }
24
78
  if (!["sandbox", "live"].includes(environment) || typeof webhookSecret !== "string" || !webhookSecret || !providerAccountId) throw new TypeError("Supply Stripe credentials, environment and account identity.");
25
79
  const live = environment === "live";
26
80
  const { validatePlan, priceFor, planFor } = createPriceBindings({ priceBindings, historicalPriceBindings, invalid });
@@ -142,6 +196,60 @@ function createStripePaymentAdapter({ apiKey, webhookSecret, environment, provid
142
196
  await verifyAccount();
143
197
  return client.prices.create({ product: productId, unit_amount: amount, currency: currency.toLowerCase(), recurring: { interval } }, { idempotencyKey: requestId });
144
198
  }
199
+ // What a top-up's Checkout session says: whose top-up it names (client_reference_id, a pointer the application's
200
+ // own record must confirm), the outcome, and what was paid.
201
+ function topUpFacts(session) {
202
+ const outcome = SESSION_OUTCOMES[`${session?.status}/${session?.payment_status}`];
203
+ if (session?.object !== "checkout.session" || session.mode !== "payment" || session.livemode !== live ||
204
+ typeof session.id !== "string" || typeof outcome !== "string") invalidTopUp();
205
+ return {
206
+ topUpId: String(session.client_reference_id ?? ""),
207
+ sessionId: session.id,
208
+ outcome,
209
+ amount: session.amount_total,
210
+ currency: String(session.currency ?? "").toUpperCase(),
211
+ paymentIntentId: id(session.payment_intent) ?? null
212
+ };
213
+ }
214
+ /**
215
+ * A one-off Checkout payment for a top-up: one line at the chosen amount, in payment mode, coming back to the
216
+ * application's return URL paid or not. The same request id answers the same session however often it is sent.
217
+ * @param {{ topUpId: string, amount: number, currency: string, name: string, description: string | null, email: string | null, returnUrl: string, requestId: string }} request
218
+ */
219
+ async function createTopUpCheckout({ topUpId, amount, currency, name, description, email, returnUrl, requestId }) {
220
+ await verifyAccount();
221
+ const tags = { jskit_top_up: topUpId };
222
+ const result = await client.checkout.sessions.create({
223
+ mode: "payment",
224
+ client_reference_id: topUpId,
225
+ line_items: [{ quantity: 1, price_data: { currency: currency.toLowerCase(), unit_amount: amount, product_data: { name, ...(description ? { description } : {}) } } }],
226
+ ...(email ? { customer_email: email } : {}),
227
+ // Stripe's receipt goes to the person who paid.
228
+ payment_intent_data: { metadata: tags, ...(email ? { receipt_email: email } : {}) },
229
+ metadata: tags,
230
+ success_url: returnUrl,
231
+ cancel_url: returnUrl
232
+ }, { idempotencyKey: requestId });
233
+ if (typeof result.id !== "string" || typeof result.url !== "string") invalidTopUp();
234
+ return { id: result.id, url: result.url };
235
+ }
236
+ /** The top-up facts of a Checkout session, read from Stripe with this adapter's own key. */
237
+ async function retrieveTopUpCheckout(sessionId) {
238
+ return topUpFacts(await client.checkout.sessions.retrieve(sessionId));
239
+ }
240
+ /**
241
+ * The top-up facts a verified event carries, or null for an event that is not a payment-mode Checkout session
242
+ * naming a top-up. A failed bank payment leaves its session complete and unpaid, so the event's type says it failed.
243
+ * @param {any} event
244
+ */
245
+ function topUpEvent(event) {
246
+ const session = event?.data?.object;
247
+ // A top-up's session names its top-up twice (see createTopUpCheckout); a Checkout payment of anything else does not.
248
+ if (!TOP_UP_EVENTS.includes(event?.type) || session?.mode !== "payment" || typeof session.client_reference_id !== "string" ||
249
+ session.metadata?.jskit_top_up !== session.client_reference_id) return null;
250
+ const facts = topUpFacts(session);
251
+ return event.type === "checkout.session.async_payment_failed" ? { ...facts, outcome: "failed" } : facts;
252
+ }
145
253
  return Object.freeze({
146
254
  validatePlan,
147
255
  verifyAccount,
@@ -151,6 +259,9 @@ function createStripePaymentAdapter({ apiKey, webhookSecret, environment, provid
151
259
  createCustomer,
152
260
  createCheckout,
153
261
  createPortal,
262
+ createTopUpCheckout,
263
+ retrieveTopUpCheckout,
264
+ topUpEvent,
154
265
  readHistory,
155
266
  readProduct,
156
267
  createProduct,
@@ -0,0 +1,97 @@
1
+ import { TOP_UP_RETURN_PARAMETER } from "../shared/topUps.js";
2
+ import { PaymentError } from "./errors.js";
3
+
4
+ // A prepaid top-up's statuses: written down before the provider hears of it (starting), its Checkout page open
5
+ // (open), paid but not cleared yet, as a bank payment is (processing), and the three it ends in: paid (credited to
6
+ // the application's balance), failed and expired.
7
+ const SETTLED_TOP_UP = Object.freeze(["paid", "failed", "expired"]);
8
+
9
+ // What each outcome the provider reports makes of each status; any other pair leaves the status as it is. Paid wins
10
+ // over every status, since the money was taken; failed and expired end only a top-up still waiting; processing only
11
+ // follows an open page. So reports arriving late, twice or out of order never undo an outcome.
12
+ const NEXT_TOP_UP_STATUS = Object.freeze({
13
+ processing: Object.freeze({ open: "processing" }),
14
+ failed: Object.freeze({ open: "failed", processing: "failed" }),
15
+ expired: Object.freeze({ open: "expired" }),
16
+ paid: Object.freeze({ open: "paid", processing: "paid", failed: "paid", expired: "paid" })
17
+ });
18
+
19
+ /**
20
+ * The status a top-up moves to when the provider reports an outcome for it.
21
+ * @param {string} status
22
+ * @param {"open" | "processing" | "paid" | "failed" | "expired"} outcome
23
+ */
24
+ function nextTopUpStatus(status, outcome) {
25
+ const moves = Object.hasOwn(NEXT_TOP_UP_STATUS, outcome) ? NEXT_TOP_UP_STATUS[outcome] : {};
26
+ return Object.hasOwn(moves, status) ? moves[status] : status;
27
+ }
28
+
29
+ /**
30
+ * Checks the amount: a whole number of the currency's smallest unit within the application's limits.
31
+ * @param {import("./types.js").PaymentTopUpOffer} offer
32
+ * @param {unknown} amount
33
+ */
34
+ function checkTopUpAmount(offer, amount) {
35
+ if (!Number.isSafeInteger(amount) || amount < offer.minimumAmount || amount > offer.maximumAmount) {
36
+ throw new PaymentError("payment_top_up_amount_invalid", "Choose a top-up amount within this application's limits, in the currency's smallest unit.", 422);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The application's return URL naming the top-up, where Checkout sends the person back, paid or not.
42
+ * @param {string} returnUrl
43
+ * @param {string} topUpId
44
+ */
45
+ function topUpReturnUrl(returnUrl, topUpId) {
46
+ const url = new URL(returnUrl);
47
+ url.searchParams.set(TOP_UP_RETURN_PARAMETER, topUpId);
48
+ return url.href;
49
+ }
50
+
51
+ /**
52
+ * What the application and its page see of a top-up: no subject, request or provider ids, and the Checkout page only
53
+ * while it is open.
54
+ * @param {import("./types.js").PaymentTopUp} topUp
55
+ */
56
+ function topUpView({ id, status, amount, currency, url }) {
57
+ return {
58
+ topUpId: id,
59
+ status,
60
+ amount,
61
+ currency,
62
+ url: status === "open" ? url : null
63
+ };
64
+ }
65
+
66
+ /**
67
+ * The top-ups a checkout service takes, checked: the validated configuration's offer, the application's credit
68
+ * function, and a provider adapter and store that carry them; null for a service without top-ups.
69
+ * @param {import("./types.js").PaymentTopUps | undefined} topUps
70
+ * @param {import("./types.js").PaymentProviderAdapter} adapter
71
+ * @param {import("./types.js").PaymentStore} store
72
+ */
73
+ function composedTopUps(topUps, adapter, store) {
74
+ if (topUps === undefined) return null;
75
+ const offer = topUps?.offer;
76
+ if (typeof offer?.currency !== "string" || !Number.isSafeInteger(offer.minimumAmount) || !Number.isSafeInteger(offer.maximumAmount) || typeof offer.name !== "string") {
77
+ throw new TypeError("Supply topUps.offer, the validated configuration's top-ups: validatePaymentConfiguration(document).topUps.");
78
+ }
79
+ // readable-check: allow method-probe - input validation: the application passes the function that adds a paid top-up to its own balance
80
+ if (typeof topUps.credit !== "function") {
81
+ throw new TypeError("Supply topUps.credit, the application's function that adds a paid top-up to its balance.");
82
+ }
83
+ // readable-check: allow method-probe - input validation: only a provider adapter with one-off Checkout payments takes top-ups
84
+ if (typeof adapter?.createTopUpCheckout !== "function") {
85
+ throw new TypeError("Top-ups take Stripe Checkout payments: compose createStripePaymentAdapter; Paddle has no top-ups.");
86
+ }
87
+ // readable-check: allow method-probe - input validation: an application's own payment store may keep no top-ups
88
+ if (typeof store?.withTopUp !== "function") {
89
+ throw new TypeError("Top-ups need a store that keeps them: PaymentStoreFeature's payments.store, or a store with createTopUp, inspectTopUp and withTopUp.");
90
+ }
91
+ return Object.freeze({
92
+ offer: Object.freeze({ ...offer }),
93
+ credit: topUps.credit
94
+ });
95
+ }
96
+
97
+ export { SETTLED_TOP_UP, checkTopUpAmount, composedTopUps, nextTopUpStatus, topUpReturnUrl, topUpView };