@jskit-ai/payments-core 0.2.37 → 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.
@@ -0,0 +1,104 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import knexLib from "knex";
4
+ import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
+ import { startFakeStripe } from "./support/fakeStripe.js";
6
+ import { createTopUpApp } from "./support/topUpApp.js";
7
+
8
+ // The two doors that settle a top-up, its verified webhook and its return page's confirmation, racing over one
9
+ // payment on MariaDB, where their transactions truly run at once: the top-up is credited once. Once-only lives in the
10
+ // top-up's row: each door moves its status to paid under that row's lock, in the transaction that writes the credit,
11
+ // so the door that waits for the lock finds it paid.
12
+
13
+ // The runtime's own MySQL connection settings (database-runtime's resolveKnexConnectionFromEnvironment).
14
+ const RUNTIME_MYSQL = Object.freeze({ supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" });
15
+
16
+ /** A database of the test's own, beside TEST_DB_NAME, dropped after the test. */
17
+ async function ownDatabase(context, suffix) {
18
+ const name = `${requireTestDatabase(process.env)}_${suffix}`;
19
+ const server = { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
20
+ const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
21
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
22
+ await admin.raw("CREATE DATABASE ??", [name]);
23
+ const knex = knexLib({ client: "mysql2", connection: { ...server, database: name, ...RUNTIME_MYSQL }, pool: { min: 0, max: 6 } });
24
+ context.after(async () => {
25
+ await knex.destroy();
26
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
27
+ await admin.destroy();
28
+ });
29
+ return knex;
30
+ }
31
+
32
+ /** A promise the test resolves itself. */
33
+ function gate() {
34
+ let open;
35
+ const opened = new Promise((resolve) => {
36
+ open = resolve;
37
+ });
38
+ return { opened, open };
39
+ }
40
+
41
+ test("the webhook and the return page settling one payment at the same moment credit it once", async (context) => {
42
+ requireTestDatabase(process.env);
43
+ const knex = await ownDatabase(context, "pay_top_up_race");
44
+ const stripe = await startFakeStripe();
45
+ context.after(() => stripe.close());
46
+ // The first door to credit stops inside its transaction, holding the top-up's row, until the other door has read it.
47
+ let hold = null;
48
+ const app = await createTopUpApp(knex, stripe, {
49
+ credit: async (request, txOptions, write) => {
50
+ await write(request, txOptions);
51
+ const held = hold;
52
+ hold = null;
53
+ if (held) {
54
+ held.entered.open();
55
+ await held.release.opened;
56
+ }
57
+ }
58
+ });
59
+ // The other door's read of the top-up in its settling transaction (its lock), sent while the first door holds the
60
+ // row; the return page reads Stripe's session first.
61
+ let watching = null;
62
+ knex.on("query", ({ sql, __knexTxId }) => {
63
+ if (watching && __knexTxId && /payment_top_ups/u.test(sql) && watching.ready()) {
64
+ watching.reached.open();
65
+ watching = null;
66
+ }
67
+ });
68
+ const doors = (topUpId) => ({
69
+ webhook: () => app.service.webhook(app.event("checkout.session.completed", topUpId)),
70
+ return: () => app.service.confirmTopUp({ actor: "tenant-a", subjectId: "tenant-a", topUpId })
71
+ });
72
+
73
+ for (const [first, second] of [["webhook", "return"], ["return", "webhook"]]) {
74
+ const { topUpId } = await app.service.topUp({ actor: "tenant-a", subjectId: "tenant-a", amount: 500, requestId: `race-${first}` });
75
+ stripe.pay(app.session(topUpId).id);
76
+ hold = { entered: gate(), release: gate() };
77
+ const { entered, release } = hold;
78
+ const opening = doors(topUpId)[first]();
79
+ await entered.opened;
80
+ const reached = gate();
81
+ const before = stripe.requests.length;
82
+ const readStripe = () => stripe.requests.slice(before).some(({ method, path }) => method === "GET" && path.startsWith("/v1/checkout/sessions/"));
83
+ watching = { reached, ready: second === "return" ? readStripe : () => true };
84
+ const closing = doors(topUpId)[second]();
85
+ await reached.opened;
86
+ release.open();
87
+ const results = await Promise.all([opening, closing]);
88
+ assert.deepEqual(results.map(({ status, credited }) => [status, credited]), [["paid", true], ["paid", false]], `${first} first`);
89
+ }
90
+ assert.deepEqual((await app.credits("tenant-a")).map(({ amount }) => amount), [500, 500], "each top-up credited once");
91
+
92
+ // And with no hand on the timing: every door at once, for several top-ups.
93
+ const started = [];
94
+ for (let index = 0; index < 8; index += 1) {
95
+ const { topUpId } = await app.service.topUp({ actor: "tenant-a", subjectId: "tenant-a", amount: 100 + index, requestId: `crowd-${index}` });
96
+ stripe.pay(app.session(topUpId).id);
97
+ started.push(topUpId);
98
+ }
99
+ const results = await Promise.all(started.flatMap((topUpId) => [doors(topUpId).webhook(), doors(topUpId).return(), doors(topUpId).webhook()]));
100
+ assert.equal(results.filter(({ credited }) => credited).length, 8);
101
+ const credits = await app.credits("tenant-a");
102
+ assert.equal(credits.length, 10);
103
+ assert.equal(new Set(credits.map(({ reference }) => reference)).size, 10, "no top-up credited twice");
104
+ });
@@ -0,0 +1,307 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import knexLib from "knex";
4
+ import Stripe from "stripe";
5
+ import { createPaddlePaymentAdapter } from "../src/server/paddle.js";
6
+ import { createPaymentCheckoutService } from "../src/server/checkout.js";
7
+ import { createStripePaymentAdapter } from "../src/server/stripe.js";
8
+ import { validatePaymentConfiguration } from "../src/shared/configuration.js";
9
+ import { TOP_UP_RETURN_PARAMETER } from "../src/shared/topUps.js";
10
+ import { startFakeStripe } from "./support/fakeStripe.js";
11
+ import { OFFER, RETURN_URL, createTopUpApp } from "./support/topUpApp.js";
12
+
13
+ // Prepaid top-ups end to end through the real Stripe SDK, against a stand-in for Stripe's API on this machine: a
14
+ // top-up starts for the subject the application authorized, within its limits; the verified webhook and the return
15
+ // page's confirmation both settle it through one path that credits a paid top-up once; and keys and stand-ins are
16
+ // refused where they would take or fake real money. The race of the two doors on one payment is proved on MariaDB
17
+ // (topUps.mysql.test.js), where two transactions truly run at once.
18
+
19
+ const TOP_UP_ID = /^[0-9a-f]{64}$/u;
20
+ const subject = (subjectId) => ({ actor: subjectId, subjectId });
21
+
22
+ /** A fresh application on its own in-memory database and its own stand-in for Stripe, closed after the test. */
23
+ async function topUpApp(t, options = {}) {
24
+ const stripe = await startFakeStripe();
25
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
26
+ t.after(async () => {
27
+ await knex.destroy();
28
+ await stripe.close();
29
+ });
30
+ return { stripe, knex, ...(await createTopUpApp(knex, stripe, options)) };
31
+ }
32
+
33
+ const sessionPosts = (stripe) => stripe.requests.filter(({ method, path }) => method === "POST" && path === "/v1/checkout/sessions");
34
+ const sessionReads = (stripe) => stripe.requests.filter(({ method, path }) => method === "GET" && path.startsWith("/v1/checkout/sessions/"));
35
+
36
+ test("a top-up starts only for a subject its actor may top up, as one Checkout payment per request", async (t) => {
37
+ const { stripe, knex, service, authorizations, session } = await topUpApp(t);
38
+ const request = { ...subject("tenant-a"), amount: 500, requestId: "top-up-1", email: "tenant@example.com" };
39
+
40
+ await assert.rejects(service.topUp({ ...request, actor: "tenant-b" }), { code: "payment_forbidden", statusCode: 403 });
41
+ await assert.rejects(service.confirmTopUp({ actor: "tenant-b", subjectId: "tenant-a", topUpId: "0".repeat(64) }), { code: "payment_forbidden" });
42
+ assert.equal(stripe.requests.length, 0, "a refused actor reaches nothing at Stripe");
43
+ assert.equal((await knex("payment_top_ups")).length, 0, "and writes nothing down");
44
+
45
+ const started = await service.topUp(request);
46
+ assert.deepEqual(authorizations.at(-1), { subjectId: "tenant-a", action: "topUp" });
47
+ assert.match(started.topUpId, TOP_UP_ID);
48
+ assert.deepEqual({ ...started, url: undefined }, { topUpId: started.topUpId, status: "open", amount: 500, currency: "USD", url: undefined });
49
+ assert.equal(started.url, `${stripe.url}/pay/${session(started.topUpId).id}`);
50
+
51
+ const paid = session(started.topUpId);
52
+ const back = `${RETURN_URL}?${TOP_UP_RETURN_PARAMETER}=${started.topUpId}`;
53
+ assert.equal(paid.mode, "payment");
54
+ assert.deepEqual(paid.metadata, { jskit_top_up: started.topUpId });
55
+ assert.deepEqual(paid.line_items, [{ quantity: "1", price_data: { currency: "usd", unit_amount: "500", product_data: { name: OFFER.name } } }]);
56
+ assert.equal(paid.customer_email, "tenant@example.com");
57
+ assert.equal(paid.payment_intent_data.receipt_email, "tenant@example.com");
58
+ assert.deepEqual([paid.success_url, paid.cancel_url], [back, back], "Checkout comes back to the return page naming the top-up, paid or not");
59
+ assert.equal(sessionPosts(stripe)[0].idempotencyKey, `top-up-${started.topUpId}`);
60
+ assert.equal(sessionPosts(stripe)[0].authorization, `Bearer ${stripe.secretKey}`);
61
+
62
+ assert.deepEqual(await service.topUp(request), started, "the same request answers the same top-up");
63
+ assert.equal(sessionPosts(stripe).length, 1, "without asking Stripe again");
64
+ await assert.rejects(service.topUp({ ...request, amount: 700 }), { code: "payment_reference_conflict", messageCode: "payments.reference.otherAmount" });
65
+ const other = await service.topUp({ ...subject("tenant-b"), amount: 500, requestId: "top-up-1" });
66
+ assert.notEqual(other.topUpId, started.topUpId, "another subject's same request id is a top-up of its own");
67
+ assert.equal((await knex("payment_top_ups")).length, 2);
68
+ });
69
+
70
+ test("a top-up's amount is a whole number of cents within the application's limits", async (t) => {
71
+ const { stripe, service } = await topUpApp(t);
72
+ for (const amount of [OFFER.minimumAmount - 1, OFFER.maximumAmount + 1, 150.5, "500", -500, Number.NaN, null]) {
73
+ await assert.rejects(service.topUp({ ...subject("tenant-a"), amount, requestId: "limits" }), { code: "payment_top_up_amount_invalid", statusCode: 422 }, String(amount));
74
+ }
75
+ assert.equal(stripe.requests.length, 0, "a refused amount reaches nothing at Stripe");
76
+ assert.equal((await service.topUp({ ...subject("tenant-a"), amount: OFFER.minimumAmount, requestId: "smallest" })).amount, OFFER.minimumAmount);
77
+ assert.equal((await service.topUp({ ...subject("tenant-a"), amount: OFFER.maximumAmount, requestId: "largest" })).amount, OFFER.maximumAmount);
78
+ await assert.rejects(service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "not valid!" }), { code: "payment_request_invalid" });
79
+ await assert.rejects(service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "described", description: "x".repeat(501) }), { code: "payment_input_invalid" });
80
+ });
81
+
82
+ test("the webhook credits a card payment once, however often Stripe reports it", async (t) => {
83
+ const { stripe, service, credits, session, event } = await topUpApp(t);
84
+ const { topUpId } = await service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "card" });
85
+ stripe.pay(session(topUpId).id);
86
+ const settled = await service.webhook(event("checkout.session.completed", topUpId));
87
+ assert.deepEqual(settled, { topUpId, status: "paid", amount: 500, currency: "USD", url: null, credited: true });
88
+ assert.deepEqual(await credits("tenant-a"), [{ reference: `top-up:${topUpId}`, amount: 500, currency: "USD" }]);
89
+ const replay = event("checkout.session.completed", topUpId);
90
+ assert.equal((await service.webhook(replay)).credited, false, "a second delivery credits nothing");
91
+ assert.equal((await service.webhook(replay)).credited, false, "nor a redelivery of the same event");
92
+ assert.equal((await service.webhook(event("checkout.session.async_payment_failed", topUpId))).status, "paid", "a late failure never undoes a payment");
93
+ assert.equal((await service.webhook(event("checkout.session.expired", topUpId, { status: "expired", payment_status: "unpaid" }))).status, "paid");
94
+ assert.equal((await credits("tenant-a")).length, 1);
95
+ assert.equal((await service.confirmTopUp({ ...subject("tenant-a"), topUpId })).credited, false, "the return page finds it paid");
96
+ assert.equal(sessionReads(stripe).length, 0, "and asks Stripe nothing about a settled top-up");
97
+ });
98
+
99
+ test("the webhook credits a bank payment when it clears, and never when it fails or the page expires", async (t) => {
100
+ const { stripe, service, credits, session, event } = await topUpApp(t);
101
+ const cleared = await service.topUp({ ...subject("tenant-a"), amount: 800, requestId: "bank-ok" });
102
+ stripe.clearing(session(cleared.topUpId).id);
103
+ assert.deepEqual(await service.webhook(event("checkout.session.completed", cleared.topUpId)),
104
+ { topUpId: cleared.topUpId, status: "processing", amount: 800, currency: "USD", url: null, credited: false });
105
+ assert.deepEqual(await credits("tenant-a"), [], "a payment still clearing credits nothing");
106
+ stripe.cleared(session(cleared.topUpId).id);
107
+ assert.equal((await service.webhook(event("checkout.session.async_payment_succeeded", cleared.topUpId))).credited, true);
108
+ assert.deepEqual(await credits("tenant-a"), [{ reference: `top-up:${cleared.topUpId}`, amount: 800, currency: "USD" }]);
109
+
110
+ const failed = await service.topUp({ ...subject("tenant-a"), amount: 900, requestId: "bank-failed" });
111
+ stripe.clearing(session(failed.topUpId).id);
112
+ await service.webhook(event("checkout.session.completed", failed.topUpId));
113
+ assert.deepEqual(await service.webhook(event("checkout.session.async_payment_failed", failed.topUpId)),
114
+ { topUpId: failed.topUpId, status: "failed", amount: 900, currency: "USD", url: null, credited: false });
115
+ assert.equal((await service.webhook(event("checkout.session.completed", failed.topUpId))).status, "failed", "a late report of the clearing payment leaves it failed");
116
+
117
+ const expired = await service.topUp({ ...subject("tenant-a"), amount: 1000, requestId: "expired" });
118
+ stripe.expire(session(expired.topUpId).id);
119
+ assert.deepEqual(await service.webhook(event("checkout.session.expired", expired.topUpId)),
120
+ { topUpId: expired.topUpId, status: "expired", amount: 1000, currency: "USD", url: null, credited: false });
121
+ assert.equal((await service.confirmTopUp({ ...subject("tenant-a"), topUpId: expired.topUpId })).status, "expired");
122
+ assert.equal((await credits("tenant-a")).length, 1, "only the cleared payment was credited");
123
+ });
124
+
125
+ test("a webhook credits the subject the top-up was written down for, and only for the session made for it", async (t) => {
126
+ const { stripe, service, credits, session, event, knex } = await topUpApp(t);
127
+ const { topUpId } = await service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "owned" });
128
+ const own = session(topUpId);
129
+ stripe.pay(own.id);
130
+
131
+ const signed = (changes) => stripe.event("checkout.session.completed", { ...own, ...changes });
132
+ assert.deepEqual(await service.webhook(signed({ id: "cs_test_other" })), { ignored: true }, "another session naming the top-up is not its payment");
133
+ assert.deepEqual(await service.webhook(signed({ client_reference_id: "f".repeat(64), metadata: { jskit_top_up: "f".repeat(64) } })), { ignored: true }, "a top-up never written down");
134
+ assert.deepEqual(await service.webhook(signed({ client_reference_id: "order-17", metadata: {} })), { ignored: true }, "another Checkout payment on the account");
135
+ await assert.rejects(service.webhook({ ...event("checkout.session.completed", topUpId), signature: "t=1,v1=forged" }), { code: "payment_signature_invalid" });
136
+ await assert.rejects(service.webhook(signed({ amount_total: 50 })), { code: "payment_provider_result_invalid", messageCode: "payments.provider.topUpAmount" });
137
+ await assert.rejects(service.webhook(signed({ currency: "eur" })), { code: "payment_provider_result_invalid", messageCode: "payments.provider.topUpAmount" });
138
+ assert.deepEqual(await credits("tenant-a"), [], "nothing above credited anything");
139
+ assert.equal(JSON.parse((await knex("payment_top_ups"))[0].payload).status, "open");
140
+
141
+ const credited = await service.webhook(signed({ metadata: { jskit_top_up: topUpId, subjectId: "tenant-b" } }));
142
+ assert.equal(credited.credited, true);
143
+ assert.deepEqual(await credits("tenant-b"), [], "metadata names no subject");
144
+ assert.equal((await credits("tenant-a")).length, 1);
145
+ });
146
+
147
+ test("a credit that fails leaves the top-up unpaid, and the next report credits it once", async (t) => {
148
+ let failing = true;
149
+ const { stripe, service, credits, session, event, knex } = await topUpApp(t, {
150
+ credit: async (request, txOptions, write) => {
151
+ await write(request, txOptions);
152
+ if (failing) throw new Error("the balance service is down");
153
+ }
154
+ });
155
+ const { topUpId } = await service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "retry" });
156
+ stripe.pay(session(topUpId).id);
157
+ await assert.rejects(service.webhook(event("checkout.session.completed", topUpId)), /the balance service is down/);
158
+ assert.deepEqual(await credits("tenant-a"), [], "the failed credit's own write rolled back with the settlement");
159
+ assert.equal(JSON.parse((await knex("payment_top_ups"))[0].payload).status, "open");
160
+ failing = false;
161
+ assert.equal((await service.confirmTopUp({ ...subject("tenant-a"), topUpId })).credited, true);
162
+ assert.equal((await service.webhook(event("checkout.session.completed", topUpId))).credited, false);
163
+ assert.equal((await credits("tenant-a")).length, 1);
164
+ });
165
+
166
+ test("the return page's confirmation reads the session from Stripe with the server's key", async (t) => {
167
+ const { stripe, service, credits, session } = await topUpApp(t);
168
+ const { topUpId } = await service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "return" });
169
+ const open = await service.confirmTopUp({ ...subject("tenant-a"), topUpId });
170
+ assert.deepEqual({ ...open, url: undefined }, { topUpId, status: "open", amount: 500, currency: "USD", url: undefined, credited: false });
171
+ assert.match(open.url, /\/pay\/cs_test_/u, "an unpaid top-up offers its Checkout page again");
172
+ assert.deepEqual(sessionReads(stripe).map(({ path, authorization }) => [path, authorization]),
173
+ [[`/v1/checkout/sessions/${session(topUpId).id}`, `Bearer ${stripe.secretKey}`]]);
174
+
175
+ stripe.clearing(session(topUpId).id);
176
+ assert.deepEqual(await service.confirmTopUp({ ...subject("tenant-a"), topUpId }),
177
+ { topUpId, status: "processing", amount: 500, currency: "USD", url: null, credited: false });
178
+ assert.deepEqual(await credits("tenant-a"), []);
179
+ stripe.cleared(session(topUpId).id);
180
+ assert.equal((await service.confirmTopUp({ ...subject("tenant-a"), topUpId })).credited, true);
181
+ assert.deepEqual(await credits("tenant-a"), [{ reference: `top-up:${topUpId}`, amount: 500, currency: "USD" }]);
182
+ assert.equal((await service.confirmTopUp({ ...subject("tenant-a"), topUpId })).credited, false);
183
+ assert.equal(sessionReads(stripe).length, 3, "a settled top-up answers without asking Stripe");
184
+
185
+ const card = await service.topUp({ ...subject("tenant-a"), amount: 600, requestId: "return-card" });
186
+ stripe.pay(session(card.topUpId).id);
187
+ assert.deepEqual(await service.confirmTopUp({ ...subject("tenant-a"), topUpId: card.topUpId }),
188
+ { topUpId: card.topUpId, status: "paid", amount: 600, currency: "USD", url: null, credited: true });
189
+
190
+ for (const topUpId of [card.topUpId, "f".repeat(64), "../etc", 7]) {
191
+ await assert.rejects(service.confirmTopUp({ ...subject("tenant-b"), topUpId }), { code: "payment_top_up_missing", statusCode: 404 }, String(topUpId));
192
+ }
193
+ });
194
+
195
+ test("a live Stripe key is refused unless APP_ENV is production; test keys work everywhere", async () => {
196
+ const options = { webhookSecret: "whsec_fixture", environment: "sandbox", providerAccountId: "acct_fixture", priceBindings: {} };
197
+ for (const appEnv of ["development", "test", "staging"]) {
198
+ for (const apiKey of ["sk_live_fixture", "rk_live_fixture"]) {
199
+ assert.throws(() => createStripePaymentAdapter({ ...options, apiKey, appEnv }), (error) => {
200
+ assert.equal(error.code, "payment_live_key_refused");
201
+ assert.equal(error.statusCode, 409);
202
+ assert.match(error.message, /only APP_ENV=production .* use a test key \(sk_test_ or rk_test_\)/u);
203
+ return true;
204
+ }, `${apiKey} in ${appEnv}`);
205
+ }
206
+ assert.equal(typeof createStripePaymentAdapter({ ...options, apiKey: "sk_test_fixture", appEnv }).createTopUpCheckout, "function");
207
+ }
208
+ assert.equal(typeof createStripePaymentAdapter({ ...options, apiKey: "sk_live_fixture", appEnv: "production", environment: "live" }).createTopUpCheckout, "function");
209
+ assert.equal(typeof createStripePaymentAdapter({ ...options, apiKey: "sk_test_fixture", appEnv: "production" }).verifyAccount, "function");
210
+ for (const appEnv of [undefined, "", "prod", "Production"]) {
211
+ assert.throws(() => createStripePaymentAdapter({ ...options, apiKey: "sk_test_fixture", appEnv }), { name: "TypeError", message: /Supply appEnv/u }, String(appEnv));
212
+ }
213
+ });
214
+
215
+ test("a stand-in for Stripe's API is taken only in development and tests", async () => {
216
+ const options = { apiKey: "sk_test_fixture", webhookSecret: "whsec_fixture", environment: "sandbox", providerAccountId: "acct_fixture", priceBindings: {} };
217
+ for (const appEnv of ["staging", "production"]) {
218
+ assert.throws(() => createStripePaymentAdapter({ ...options, appEnv, apiBaseUrl: "http://127.0.0.1:12111" }), { code: "payment_stand_in_refused", statusCode: 409 }, appEnv);
219
+ }
220
+ for (const apiBaseUrl of ["http://127.0.0.1:12111/v1", "http://user:secret@127.0.0.1:12111", "ftp://127.0.0.1", "http://127.0.0.1:12111/?x=1"]) {
221
+ assert.throws(() => createStripePaymentAdapter({ ...options, appEnv: "test", apiBaseUrl }), { name: "TypeError", message: /stand-in's origin alone/u }, apiBaseUrl);
222
+ }
223
+ const stripe = await startFakeStripe({ secretKey: options.apiKey });
224
+ try {
225
+ const adapter = createStripePaymentAdapter({ ...options, appEnv: "development", apiBaseUrl: stripe.url, providerAccountId: stripe.accountId });
226
+ assert.equal((await adapter.verifyAccount()).accountId, stripe.accountId);
227
+ assert.deepEqual(stripe.requests.map(({ path }) => path), ["/v1/account", "/v1/balance"], "the SDK's requests went to the stand-in");
228
+ } finally { await stripe.close(); }
229
+ });
230
+
231
+ test("a live merchant takes no top-up outside production", async () => {
232
+ const adapter = createStripePaymentAdapter({ client: new Stripe("sk_test_unused"), appEnv: "staging", webhookSecret: "whsec_fixture", environment: "live", providerAccountId: "acct_live", priceBindings: {} });
233
+ const service = createPaymentCheckoutService({
234
+ appEnv: "staging",
235
+ adapter,
236
+ store: { withTopUp: async () => assert.fail("nothing is written down"), createTopUp: async () => assert.fail("nothing is written down") },
237
+ payments: {},
238
+ merchantScope: { applicationId: "app", integrationId: "billing", providerAccountId: "acct_live", environment: "live" },
239
+ returnUrl: RETURN_URL,
240
+ authorize: async () => true,
241
+ topUps: { offer: OFFER, credit: async () => assert.fail("nothing is credited") }
242
+ });
243
+ await assert.rejects(service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "live" }), { code: "payment_sandbox_only", statusCode: 409 });
244
+ });
245
+
246
+ test("a configuration sells plans, top-ups or both; one selling nothing is told about its empty plans first", () => {
247
+ const document = (payments) => ({
248
+ integrations: { billing: { provider: "stripe", accountMode: "shared", authentication: { method: "api-key", secretRef: "env:STRIPE_KEY" } } },
249
+ extensions: { payments: { version: 1, environments: { sandbox: { integrationId: "billing", providerAccountId: "acct_fixture", webhookSecretRef: "env:STRIPE_WEBHOOK_SECRET", returnUrlRef: "env:APP_URL" } }, ...payments } }
250
+ });
251
+ assert.deepEqual(validatePaymentConfiguration(document({ plans: {}, topUps: OFFER })).topUps, OFFER);
252
+ assert.throws(() => validatePaymentConfiguration(document({ plans: {} })), (error) => {
253
+ assert.equal(error.code, "payment_configuration_invalid");
254
+ assert.deepEqual(error.fieldErrors[0], { path: "extensions.payments/plans", message: "must NOT have fewer than 1 properties" },
255
+ "the first error, which an editor shows above the form, is the one it showed before top-ups existed");
256
+ return true;
257
+ });
258
+ for (const topUps of [{ ...OFFER, minimumAmount: 49 }, { ...OFFER, maximumAmount: 100000000 }, { ...OFFER, currency: "usd" }, { ...OFFER, name: "" }, { ...OFFER, minimumAmount: 100.5 }, { ...OFFER, extra: true }]) {
259
+ assert.throws(() => validatePaymentConfiguration(document({ plans: {}, topUps })), { code: "payment_configuration_invalid" }, JSON.stringify(topUps));
260
+ }
261
+ assert.throws(() => validatePaymentConfiguration(document({ plans: {}, topUps: { ...OFFER, minimumAmount: 5000, maximumAmount: 1000 } })), (error) => {
262
+ assert.deepEqual(error.fieldErrors, [{ path: "extensions.payments/topUps/maximumAmount", message: "Make the largest top-up at least the smallest.", code: "payments.configuration.topUpRange", params: {} }]);
263
+ return true;
264
+ });
265
+ });
266
+
267
+ test("top-ups are Stripe's: a Paddle connection with top-ups fails validation and composition, naming the fix", async (t) => {
268
+ const document = {
269
+ integrations: { billing: { provider: "paddle", accountMode: "shared", authentication: { method: "api-key", secretRef: "env:PADDLE_KEY" }, settings: { environment: "sandbox" } } },
270
+ extensions: { payments: {
271
+ version: 1,
272
+ environments: { sandbox: { integrationId: "billing", providerAccountId: "acct_fixture", webhookSecretRef: "env:PADDLE_WEBHOOK_SECRET", returnUrlRef: "env:APP_URL", taxCategory: "saas", publicClientTokenRef: "env:PADDLE_CLIENT_TOKEN" } },
273
+ plans: {},
274
+ topUps: OFFER
275
+ } }
276
+ };
277
+ assert.throws(() => validatePaymentConfiguration(document), (error) => {
278
+ assert.equal(error.code, "payment_configuration_invalid");
279
+ assert.deepEqual(error.fieldErrors, [{
280
+ path: "extensions.payments/environments/sandbox/integrationId",
281
+ message: "Top-ups take Stripe Checkout payments: select a Stripe connection for sandbox, or remove topUps.",
282
+ code: "payments.configuration.paddleTopUps",
283
+ params: { environment: "sandbox" }
284
+ }]);
285
+ return true;
286
+ });
287
+ const paddle = createPaddlePaymentAdapter({ client: {}, webhookSecret: "fixture", environment: "sandbox", priceBindings: {} });
288
+ const { store } = await topUpApp(t);
289
+ assert.throws(() => createPaymentCheckoutService({
290
+ appEnv: "test", adapter: paddle, store, payments: {}, merchantScope: { applicationId: "app", integrationId: "billing", providerAccountId: "acct_fixture", environment: "sandbox" },
291
+ returnUrl: RETURN_URL, authorize: async () => true, topUps: { offer: OFFER, credit: async () => {} }
292
+ }), { name: "TypeError", message: /Paddle has no top-ups/u });
293
+ });
294
+
295
+ test("a service composed without top-ups refuses them, and with them requires the offer and the credit", async (t) => {
296
+ const { service } = await topUpApp(t, { topUps: undefined });
297
+ await assert.rejects(service.topUp({ ...subject("tenant-a"), amount: 500, requestId: "none" }), { code: "payment_top_ups_unavailable", statusCode: 409 });
298
+ await assert.rejects(service.confirmTopUp({ ...subject("tenant-a"), topUpId: "f".repeat(64) }), { code: "payment_top_ups_unavailable" });
299
+ for (const [topUps, message] of [
300
+ [null, /topUps\.offer/u],
301
+ [{ credit: async () => {} }, /topUps\.offer/u],
302
+ [{ offer: { ...OFFER, currency: undefined }, credit: async () => {} }, /topUps\.offer/u],
303
+ [{ offer: OFFER }, /topUps\.credit/u]
304
+ ]) {
305
+ await assert.rejects(topUpApp(t, { topUps }), { name: "TypeError", message });
306
+ }
307
+ });