@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.
@@ -50,7 +50,37 @@
50
50
  */
51
51
 
52
52
  /**
53
- * Where payment accounts and catalogues are kept: the store PaymentStoreFeature
53
+ * One prepaid top-up, as the store keeps it. Its subject is the one the application authorized when it started the
54
+ * top-up: a provider's event or a return page only names the top-up.
55
+ * @typedef {object} PaymentTopUp
56
+ * @property {string} id
57
+ * @property {string} subjectId
58
+ * @property {string} requestId
59
+ * @property {number} amount In the currency's smallest unit.
60
+ * @property {string} currency
61
+ * @property {"starting" | "open" | "processing" | "paid" | "failed" | "expired"} status
62
+ * @property {string | null} sessionId The provider's Checkout session, once it answered.
63
+ * @property {string | null} url Its Checkout page.
64
+ * @property {string | null} paymentIntentId The provider's payment, once paid.
65
+ * @property {number} createdAt UTC milliseconds.
66
+ * @property {number | null} settledAt When it became paid, failed or expired.
67
+ */
68
+
69
+ /**
70
+ * The options of a transaction a store's lock holds, which handle calls take to join it.
71
+ * @typedef {Readonly<{ context?: object | null, trx: object }>} PaymentTransactionOptions
72
+ */
73
+
74
+ /**
75
+ * A top-up held under the store's lock while work runs: the top-up, which the work changes in place (null when there
76
+ * is none), and the options of the transaction the lock holds.
77
+ * @typedef {object} PaymentTopUpTransaction
78
+ * @property {PaymentTopUp | null} topUp
79
+ * @property {PaymentTransactionOptions} options
80
+ */
81
+
82
+ /**
83
+ * Where payment accounts, catalogues and top-ups are kept: the store PaymentStoreFeature
54
84
  * provides as `payments.store`, or the application's own store. Each `with*` call runs its work under the
55
85
  * record's lock and saves the state the work leaves.
56
86
  * @typedef {object} PaymentStore
@@ -61,6 +91,47 @@
61
91
  * @property {(scope: PaymentMerchantScope, customerId: string) => Promise<string | null>} resolveCustomer The subject a provider customer is bound to.
62
92
  * @property {(scope: PaymentMerchantScope) => Promise<PaymentCatalogueState>} inspectCatalogue
63
93
  * @property {<T>(scope: PaymentMerchantScope, work: (state: PaymentCatalogueState) => Promise<T>) => Promise<T>} withCatalogue
94
+ * @property {(scope: PaymentMerchantScope, topUpId: string) => Promise<PaymentTopUp | null>} inspectTopUp
95
+ * @property {(scope: PaymentMerchantScope, topUp: PaymentTopUp) => Promise<PaymentTopUp>} createTopUp
96
+ * Writes a top-up down unless one with its id exists, and answers the stored one.
97
+ * @property {<T>(scope: PaymentMerchantScope, topUpId: string, work: (held: PaymentTopUpTransaction) => Promise<T>) => Promise<T>} withTopUp
98
+ */
99
+
100
+ /**
101
+ * An application's prepaid top-ups: the validated configuration's `topUps`.
102
+ * @typedef {object} PaymentTopUpOffer
103
+ * @property {string} name The product name on the Checkout page.
104
+ * @property {string} currency
105
+ * @property {number} minimumAmount In the currency's smallest unit.
106
+ * @property {number} maximumAmount
107
+ */
108
+
109
+ /**
110
+ * The application's own balance gains a paid top-up, inside the transaction that settles it. Pass `options` to the
111
+ * handle calls that write the credit (`balances.withTransaction({ ...options, joinOnly: true }, work)`, or
112
+ * `{ ...options, context }` under the application's own context): they join that transaction, so the credit and the
113
+ * top-up's move to paid commit together or not at all. It is called once per paid top-up, and again only when its
114
+ * transaction rolled back (the credit failed, or the database ran the transaction again as a deadlock victim), so
115
+ * write nothing outside the transaction. `reference` is stable per top-up, for the application's ledger.
116
+ * @typedef {(credit: { reference: string, subjectId: string, amount: number, currency: string }, options: PaymentTransactionOptions) => Promise<void>} PaymentTopUpCredit
117
+ */
118
+
119
+ /**
120
+ * Top-ups a checkout service takes.
121
+ * @typedef {object} PaymentTopUps
122
+ * @property {PaymentTopUpOffer} offer
123
+ * @property {PaymentTopUpCredit} credit
124
+ */
125
+
126
+ /**
127
+ * What a provider says of a top-up's Checkout session.
128
+ * @typedef {object} PaymentTopUpFacts
129
+ * @property {string} topUpId The top-up the session names, a pointer the stored top-up must confirm.
130
+ * @property {string} sessionId
131
+ * @property {"open" | "processing" | "paid" | "failed" | "expired"} outcome
132
+ * @property {number} amount What the session took, in the currency's smallest unit.
133
+ * @property {string} currency
134
+ * @property {string | null} paymentIntentId
64
135
  */
65
136
 
66
137
  /**
@@ -100,6 +171,10 @@
100
171
  * @property {(request: { id: string, name: string, requestId: string }) => Promise<{ id: string }>} renameProduct
101
172
  * @property {(priceId: string) => Promise<PaymentProviderPrice>} readPrice
102
173
  * @property {(request: { productId: string, amount: number, currency: string, interval: string, requestId: string }) => Promise<{ id: string }>} createPrice
174
+ * @property {(request: { topUpId: string, amount: number, currency: string, name: string, description: string | null, email: string | null, returnUrl: string, requestId: string }) => Promise<PaymentProviderPage>} [createTopUpCheckout]
175
+ * Stripe only: a one-off Checkout payment for a top-up.
176
+ * @property {(sessionId: string) => Promise<PaymentTopUpFacts>} [retrieveTopUpCheckout] Stripe only.
177
+ * @property {(event: any) => PaymentTopUpFacts | null} [topUpEvent] Stripe only: a verified event's top-up facts.
103
178
  */
104
179
 
105
180
  export {};
@@ -54,8 +54,17 @@ function validatePaymentConfiguration(document) {
54
54
  fieldErrors.push({ path: `${path}/publicClientTokenRef`, message: "Set the Env reference for this environment's Paddle public client token.",
55
55
  code: "payments.configuration.paddleClientToken", params: {} });
56
56
  }
57
+ // Top-ups are one-off Stripe Checkout payments; nothing takes them through Paddle.
58
+ if (value.topUps) {
59
+ fieldErrors.push({ path: `${path}/integrationId`, message: `Top-ups take Stripe Checkout payments: select a Stripe connection for ${environment}, or remove topUps.`,
60
+ code: "payments.configuration.paddleTopUps", params: { environment } });
61
+ }
57
62
  }
58
63
  }
64
+ if (value.topUps && value.topUps.minimumAmount > value.topUps.maximumAmount) {
65
+ fieldErrors.push({ path: "extensions.payments/topUps/maximumAmount", message: "Make the largest top-up at least the smallest.",
66
+ code: "payments.configuration.topUpRange", params: {} });
67
+ }
59
68
  if (fieldErrors.length) throw new PaymentConfigurationError(fieldErrors[0].message, fieldErrors, {
60
69
  messageCode: fieldErrors[0].code, messageParams: fieldErrors[0].params
61
70
  });
@@ -0,0 +1,5 @@
1
+ // The query parameter on the application's return URL that names the top-up a person comes back from: Stripe
2
+ // Checkout sends them to `<returnUrl>?paymentTopUp=<topUpId>`, paid or not, and the return page confirms that top-up.
3
+ const TOP_UP_RETURN_PARAMETER = "paymentTopUp";
4
+
5
+ export { TOP_UP_RETURN_PARAMETER };
@@ -16,7 +16,7 @@ const secret = 'test-signing-secret';
16
16
 
17
17
  test('official SDK signature verification rejects mutation and expired delivery for both providers', async () => {
18
18
  const stripeClient = new Stripe('sk_test_fixture', { maxNetworkRetries: 0 });
19
- const stripe = createStripePaymentAdapter({ client: stripeClient, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' } });
19
+ const stripe = createStripePaymentAdapter({ appEnv: 'test', client: stripeClient, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' } });
20
20
  const raw = Buffer.from(JSON.stringify({ id: 'evt_a', type: 'customer.created', livemode: false, data: { object: { id: 'cus_a' } } }));
21
21
  const header = stripeClient.webhooks.generateTestHeaderString({ payload: raw.toString(), secret });
22
22
  assert.equal((await stripe.verifyEvent(raw, header)).id, 'evt_a');
@@ -86,7 +86,7 @@ test('Stripe reconciliation loads current subscription and validates invoice acc
86
86
  const subscription = { id: 'sub_a', customer: 'cus_a', livemode: false, status: 'active', items: { has_more: false, data: [{ quantity: 1, price: { id: 'price_a' }, current_period_end: 20000 }] } };
87
87
  const invoice = { id: 'in_a', customer: 'cus_a', livemode: false, status: 'paid', billing_reason: 'subscription_cycle', parent: { subscription_details: { subscription: 'sub_a' } }, lines: { has_more: false, data: [{ quantity: 1, parent: { subscription_item_details: { proration: false } }, pricing: { price_details: { price: 'price_a' } }, period: { end: 20000 } }] } };
88
88
  const client = { accounts: { retrieve: async () => ({ id: 'acct_a' }) }, balance: { retrieve: async () => ({ livemode: false }) }, subscriptions: { retrieve: async () => subscription }, invoices: { retrieve: async () => invoice } };
89
- const adapter = createStripePaymentAdapter({ client, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' } });
89
+ const adapter = createStripePaymentAdapter({ appEnv: 'test', client, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' } });
90
90
  const event = { type: 'invoice.paid', data: { object: { id: 'in_a' } } };
91
91
  assert.equal((await adapter.loadEvent(event)).renewal.planId, 'pro');
92
92
  invoice.status = 'open';
@@ -109,7 +109,7 @@ test('Stripe reconciliation loads current subscription and validates invoice acc
109
109
 
110
110
  test('signed standalone Stripe invoices are ignored before customer lookup; malformed and tampered events fail', async () => {
111
111
  const client = new Stripe('sk_test_fixture', { maxNetworkRetries: 0 });
112
- const adapter = createStripePaymentAdapter({ client, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: {} });
112
+ const adapter = createStripePaymentAdapter({ appEnv: 'test', client, webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: {} });
113
113
  let reconciliations = 0;
114
114
  const service = createPaymentCheckoutService({ appEnv: 'test', adapter, merchantScope: scope, returnUrl: 'https://app.example/billing', authorize: async () => false,
115
115
  payments: { async reconcileEvent() { reconciliations++; } } });
@@ -180,7 +180,7 @@ test('signed subscription lifecycle updates app access without crossing subjects
180
180
  plans: { pro: { features: ['export'], renewalCredits: 100 } }
181
181
  } });
182
182
  const adapter = provider === 'stripe'
183
- ? createStripePaymentAdapter({ webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' }, client: {
183
+ ? createStripePaymentAdapter({ appEnv: 'test', webhookSecret: secret, environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: { pro: 'price_a' }, client: {
184
184
  webhooks: stripeSdk.webhooks,
185
185
  accounts: { retrieve: async () => ({ id: 'acct_a' }) }, balance: { retrieve: async () => ({ livemode: false }) },
186
186
  subscriptions: { retrieve: async () => { loads++; return { id: 'sub_a', customer: customerId, livemode: false, status, items: { has_more: false, data: [{ quantity: 1, price: { id: 'price_a' }, current_period_end: end / 1000 }] } }; } }
@@ -6,7 +6,9 @@ import knex from 'knex';
6
6
  import migration from '../migrations/payments_core_initial.cjs';
7
7
  import { validatePaymentConfiguration } from '../src/shared/configuration.js';
8
8
  import { createPaymentService } from '../src/server/service.js';
9
+ import { createPaymentCheckoutService } from '../src/server/checkout.js';
9
10
  import { createTestPaymentStore } from './support/paymentStore.js';
11
+ import { migratePayments } from './support/migrations.js';
10
12
 
11
13
  const fixture = JSON.parse(await readFile(new URL('../contracts/conformance.json', import.meta.url), 'utf8'));
12
14
  const schema = JSON.parse(await readFile(new URL('../contracts/configuration.schema.json', import.meta.url), 'utf8'));
@@ -25,7 +27,8 @@ test('payment binding errors identify the field to repair without returning cred
25
27
  ['missing-connection', 'integrationId', /shared Stripe or Paddle/],
26
28
  ['inline-api-key', 'integrationId', /Env reference/],
27
29
  ['paddle-environment-mismatch', 'integrationId', /configured for sandbox/],
28
- ['paddle-client-token-missing', 'publicClientTokenRef', /public client token/]
30
+ ['paddle-client-token-missing', 'publicClientTokenRef', /public client token/],
31
+ ['paddle-top-ups', 'integrationId', /Top-ups take Stripe Checkout payments/]
29
32
  ];
30
33
  for (const [id, field, message] of cases) {
31
34
  const item = fixture.configurationCases.find((entry) => entry.id === id);
@@ -37,6 +40,11 @@ test('payment binding errors identify the field to repair without returning cred
37
40
  return true;
38
41
  });
39
42
  }
43
+ const inverted = fixture.configurationCases.find((entry) => entry.id === 'top-up-range-inverted').document;
44
+ assert.throws(() => validatePaymentConfiguration(inverted), (error) => {
45
+ assert.deepEqual(error.fieldErrors.map((entry) => entry.path), ['extensions.payments/topUps/maximumAmount']);
46
+ return true;
47
+ });
40
48
  const document = structuredClone(fixture.configurationCases.find((entry) => entry.id === 'paddle-sandbox').document);
41
49
  delete document.extensions.payments.environments.sandbox.taxCategory;
42
50
  delete document.extensions.payments.environments.sandbox.publicClientTokenRef;
@@ -75,3 +83,70 @@ test('portable account sequence defines actual credit, renewal, expiry and subje
75
83
  }
76
84
  } finally { await migration.down(db); await db.destroy(); }
77
85
  });
86
+
87
+ test('portable top-up sequence defines when a top-up is credited, whichever door reports its payment', async () => {
88
+ const scenario = fixture.topUpScenario;
89
+ const db = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
90
+ await migratePayments(db);
91
+ await db.schema.createTable('conformance_credits', (table) => {
92
+ table.increments('id');
93
+ table.string('subject_id').notNullable();
94
+ table.integer('amount').notNullable();
95
+ table.string('currency').notNullable();
96
+ });
97
+ const store = await createTestPaymentStore(db);
98
+ const configuration = validatePaymentConfiguration(scenario.document);
99
+ const { subjectId, ...merchantScope } = scenario.scope;
100
+ // The controlled provider: each top-up's Checkout session, and the facts the step's door reports for it.
101
+ const sessions = new Map();
102
+ let reported = null;
103
+ const adapter = {
104
+ async createTopUpCheckout({ topUpId }) {
105
+ const id = `cs_fixture_${sessions.size + 1}`;
106
+ sessions.set(topUpId, id);
107
+ return { id, url: `https://checkout.example/${id}` };
108
+ },
109
+ async retrieveTopUpCheckout() { return reported; },
110
+ async verifyEvent(rawBody) { return JSON.parse(rawBody.toString()); },
111
+ topUpEvent: (event) => event.facts
112
+ };
113
+ const service = createPaymentCheckoutService({
114
+ appEnv: 'test', adapter, store, payments: {}, merchantScope, returnUrl: 'https://app.example/credits',
115
+ authorize: async (actor, request) => actor === request.subjectId && request.action === 'topUp',
116
+ topUps: {
117
+ offer: configuration.topUps,
118
+ credit: async (credit, options) => {
119
+ await options.trx('conformance_credits').insert({ subject_id: credit.subjectId, amount: credit.amount, currency: credit.currency });
120
+ }
121
+ }
122
+ });
123
+ const named = new Map();
124
+ const compare = (actual, expected) => {
125
+ if (!expected || typeof expected !== 'object' || Array.isArray(expected)) return assert.deepEqual(actual, expected);
126
+ for (const [key, value] of Object.entries(expected)) compare(actual[key], value);
127
+ };
128
+ try {
129
+ for (const step of scenario.steps) {
130
+ const subject = step.subjectId ?? subjectId;
131
+ let run;
132
+ if (step.operation === 'topUp') {
133
+ run = async () => {
134
+ const started = await service.topUp({ actor: subject, subjectId: subject, ...step.input });
135
+ named.set(step.topUp, started.topUpId);
136
+ return started;
137
+ };
138
+ } else if (step.operation === 'settle') {
139
+ const topUpId = named.get(step.topUp);
140
+ reported = { ...step.facts, topUpId, sessionId: sessions.get(topUpId), paymentIntentId: null };
141
+ run = step.door === 'webhook'
142
+ ? () => service.webhook({ rawBody: Buffer.from(JSON.stringify({ facts: reported })), signature: 'fixture' })
143
+ : () => service.confirmTopUp({ actor: subject, subjectId: subject, topUpId });
144
+ } else {
145
+ assert.equal(step.operation, 'credits');
146
+ run = async () => (await db('conformance_credits').orderBy('id')).map((row) => ({ subjectId: row.subject_id, amount: row.amount, currency: row.currency }));
147
+ }
148
+ if (step.error) await assert.rejects(run(), { code: step.error }, JSON.stringify(step));
149
+ else compare(await run(), step.expect);
150
+ }
151
+ } finally { await db.destroy(); }
152
+ });
@@ -67,7 +67,7 @@ test('Stripe history uses customer-filtered single pages, includes canceled subs
67
67
  const client = { accounts: { retrieve: async () => ({ id: accountId }) }, balance: { retrieve: async () => ({ livemode: false }) },
68
68
  invoices: { list: async (query) => { queries.push(query); return { data: [invoice], has_more: true }; } },
69
69
  subscriptions: { list: async (query) => { queries.push(query); return { data: [{ id: 'sub_a', customer: 'cus_a', livemode: false, created: 1700000000, status: 'canceled', metadata: { hidden: true } }], has_more: false }; } } };
70
- const adapter = createStripePaymentAdapter({ client, webhookSecret: 'fixture', environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: {} });
70
+ const adapter = createStripePaymentAdapter({ appEnv: 'test', client, webhookSecret: 'fixture', environment: 'sandbox', providerAccountId: 'acct_a', priceBindings: {} });
71
71
  const result = await adapter.readHistory({ customerId: 'cus_a', collection: 'transactions', after: 'in_previous' });
72
72
  assert.deepEqual(queries[0], { customer: 'cus_a', limit: 20, starting_after: 'in_previous' });
73
73
  assert.deepEqual(result, { collection: 'transactions', items: [{ id: 'in_a', kind: 'invoice', status: 'open', createdAt: '2023-11-14T22:13:20.000Z', currency: 'USD', totalMinor: '1200', paidMinor: '0' }], nextCursor: 'in_a' });
@@ -74,6 +74,8 @@ test("configuration errors carry codes whose English matches each field error",
74
74
  "payments.configuration.paddleClientToken",
75
75
  "payments.configuration.paddleEnvironment",
76
76
  "payments.configuration.paddleTaxCategory",
77
- "payments.configuration.sharedConnectionRequired"
77
+ "payments.configuration.paddleTopUps",
78
+ "payments.configuration.sharedConnectionRequired",
79
+ "payments.configuration.topUpRange"
78
80
  ]);
79
81
  });
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import knexLib from "knex";
4
4
  import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
- import migration from "../migrations/payments_core_initial.cjs";
5
+ import { migratePayments } from "./support/migrations.js";
6
6
  import { createPaymentService } from "../src/server/service.js";
7
7
  import { validatePaymentConfiguration } from "../src/shared/configuration.js";
8
8
  import { checkForeignKeys } from "@jskit-ai/resource-runtime/server";
@@ -30,7 +30,7 @@ async function ownDatabase(context, suffix) {
30
30
  await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
31
31
  await admin.destroy();
32
32
  });
33
- await migration.up(knex);
33
+ await migratePayments(knex);
34
34
  return knex;
35
35
  }
36
36
 
@@ -67,7 +67,7 @@ test("the store refuses incomplete scopes and identities before any work runs",
67
67
  requireTestDatabase(process.env);
68
68
  const store = await createTestPaymentStore(await ownDatabase(context, "da_pay_refusals"));
69
69
  assert.ok(Object.isFrozen(store));
70
- assert.deepEqual(Object.keys(store), ["inspect", "withAccount", "bindCustomer", "resolveCustomer", "inspectCatalogue", "withCatalogue"]);
70
+ assert.deepEqual(Object.keys(store), ["inspect", "withAccount", "bindCustomer", "resolveCustomer", "inspectCatalogue", "withCatalogue", "inspectTopUp", "createTopUp", "withTopUp"]);
71
71
 
72
72
  for (const [changes, message] of [
73
73
  [{ applicationId: "" }, "Payment scope requires applicationId."],
@@ -6,7 +6,7 @@ import { EventProvider } from "@jskit-ai/kernel/server/runtime";
6
6
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
7
7
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
8
8
  import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
9
- import migration from "../migrations/payments_core_initial.cjs";
9
+ import { migratePayments } from "./support/migrations.js";
10
10
  import { PaymentStoreFeature } from "../src/server/storage.js";
11
11
 
12
12
  const merchant = Object.freeze({ applicationId: "app", integrationId: "billing", providerAccountId: "acct_test", environment: "sandbox" });
@@ -14,7 +14,7 @@ const merchant = Object.freeze({ applicationId: "app", integrationId: "billing",
14
14
  test("PaymentStoreFeature owns the payment tables and provides the store on their handles as payments.store", async (t) => {
15
15
  const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true, pool: { min: 1, max: 1 } });
16
16
  t.after(() => knex.destroy());
17
- await migration.up(knex);
17
+ await migratePayments(knex);
18
18
  const resources = await createTestResourceRuntime({ knex });
19
19
  let store = null;
20
20
  const runtime = createCapabilityRuntime({
@@ -34,7 +34,8 @@ test("PaymentStoreFeature owns the payment tables and provides the store on thei
34
34
  ["payment_accounts", "payments.store"],
35
35
  ["payment_entries", "payments.store"],
36
36
  ["payment_customers", "payments.store"],
37
- ["payment_catalogues", "payments.store"]
37
+ ["payment_catalogues", "payments.store"],
38
+ ["payment_top_ups", "payments.store"]
38
39
  ]);
39
40
  const scope = { ...merchant, subjectId: "tenant-a" };
40
41
  assert.equal(await store.withAccount(scope, async ({ state, record }) => {
@@ -50,4 +51,15 @@ test("PaymentStoreFeature owns the payment tables and provides the store on thei
50
51
  state.revision = 1;
51
52
  });
52
53
  assert.deepEqual(await store.inspectCatalogue(merchant), { plans: {}, history: [], revision: 1 });
54
+ const topUp = { id: "top-up-1", subjectId: "tenant-a", status: "starting" };
55
+ assert.deepEqual(await store.createTopUp(merchant, topUp), topUp);
56
+ assert.deepEqual(await store.createTopUp(merchant, { ...topUp, status: "other" }), topUp, "a top-up is written once; a repeat answers the first");
57
+ assert.equal(await store.withTopUp(merchant, "top-up-1", async (held) => {
58
+ held.topUp.status = "open";
59
+ return "opened";
60
+ }), "opened");
61
+ assert.deepEqual(await store.inspectTopUp(merchant, "top-up-1"), { ...topUp, status: "open" });
62
+ assert.equal(await store.withTopUp(merchant, "top-up-2", async (held) => held.topUp), null, "the lock creates no top-up");
63
+ assert.equal(await store.inspectTopUp(merchant, "top-up-2"), null);
64
+ assert.equal(await store.inspectTopUp({ ...merchant, applicationId: "other" }, "top-up-1"), null, "another merchant sees no top-up of this one");
53
65
  });
@@ -0,0 +1,112 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import http from "node:http";
3
+ import Stripe from "stripe";
4
+
5
+ // A stand-in for the part of Stripe's API that top-ups use, for the real Stripe SDK to talk to through the adapter's
6
+ // apiBaseUrl: the account and balance the adapter verifies, and Checkout sessions created (once per idempotency key)
7
+ // and read back. The test moves a session on (pay, clearing, expire) as Stripe would, and signs webhook events with
8
+ // the endpoint's secret as Stripe does. It records each request, so a test sees what reached "Stripe". Nothing here
9
+ // leaves the machine.
10
+
11
+ /** Stripe's form encoding read back into objects: `line_items[0][price_data][currency]=usd`. */
12
+ function formParams(text) {
13
+ const result = {};
14
+ for (const [name, value] of new URLSearchParams(text)) {
15
+ const keys = name.replace(/\]/gu, "").split("[");
16
+ let at = result;
17
+ keys.forEach((key, index) => {
18
+ if (index === keys.length - 1) at[key] = value;
19
+ else at = at[key] ??= /^\d+$/u.test(keys[index + 1]) ? [] : {};
20
+ });
21
+ }
22
+ return result;
23
+ }
24
+
25
+ /**
26
+ * @param {{ accountId?: string, secretKey?: string, webhookSecret?: string, retrieveDelayMs?: number }} [options]
27
+ * `retrieveDelayMs` holds each session read that long, to widen a race.
28
+ */
29
+ export async function startFakeStripe({ accountId = "acct_stand_in", secretKey = "sk_test_stand_in", webhookSecret = "whsec_stand_in", retrieveDelayMs = 0 } = {}) {
30
+ const sessions = new Map();
31
+ const byKey = new Map();
32
+ const requests = [];
33
+ const signer = new Stripe(secretKey);
34
+ let count = 0;
35
+ let url = "";
36
+
37
+ const server = http.createServer(async (request, response) => {
38
+ let body = "";
39
+ for await (const chunk of request) body += chunk;
40
+ const address = new URL(request.url, "http://stand-in");
41
+ requests.push({ method: request.method, path: address.pathname, authorization: request.headers.authorization, idempotencyKey: request.headers["idempotency-key"] ?? null });
42
+ const json = (status, value) => {
43
+ response.writeHead(status, { "content-type": "application/json", "request-id": `req_${++count}` });
44
+ response.end(JSON.stringify(value));
45
+ };
46
+ const refused = (status, message) => json(status, { error: { type: "invalid_request_error", message } });
47
+ if (request.headers.authorization !== `Bearer ${secretKey}`) return refused(401, "Invalid API Key provided.");
48
+ if (request.method === "GET" && address.pathname === "/v1/account") {
49
+ return json(200, { id: accountId, object: "account", charges_enabled: true, payouts_enabled: true });
50
+ }
51
+ if (request.method === "GET" && address.pathname === "/v1/balance") return json(200, { object: "balance", livemode: false, available: [], pending: [] });
52
+ if (request.method === "POST" && address.pathname === "/v1/checkout/sessions") {
53
+ const key = request.headers["idempotency-key"];
54
+ if (key && byKey.has(key)) return json(200, sessions.get(byKey.get(key)));
55
+ const params = formParams(body);
56
+ const item = params.line_items?.[0];
57
+ const id = `cs_test_${randomBytes(8).toString("hex")}`;
58
+ const session = {
59
+ ...params,
60
+ id,
61
+ object: "checkout.session",
62
+ livemode: false,
63
+ url: `${url}/pay/${id}`,
64
+ status: "open",
65
+ payment_status: "unpaid",
66
+ payment_intent: null,
67
+ currency: item?.price_data?.currency,
68
+ amount_total: Number(item?.price_data?.unit_amount) * Number(item?.quantity || 1)
69
+ };
70
+ sessions.set(id, session);
71
+ if (key) byKey.set(key, id);
72
+ return json(200, session);
73
+ }
74
+ const read = /^\/v1\/checkout\/sessions\/(cs_test_\w+)$/u.exec(address.pathname);
75
+ if (request.method === "GET" && read) {
76
+ if (retrieveDelayMs) await new Promise((resolve) => setTimeout(resolve, retrieveDelayMs));
77
+ const session = sessions.get(read[1]);
78
+ return session ? json(200, session) : refused(404, "No such checkout.session");
79
+ }
80
+ return refused(404, "Unrecognized request URL");
81
+ });
82
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
83
+ url = `http://127.0.0.1:${server.address().port}`;
84
+
85
+ const change = (id, values) => Object.assign(sessions.get(id), values);
86
+ return {
87
+ url,
88
+ accountId,
89
+ secretKey,
90
+ webhookSecret,
91
+ sessions,
92
+ requests,
93
+ /** The person pays on the session's page: card payments are paid at once. */
94
+ pay: (id) => change(id, { status: "complete", payment_status: "paid", payment_intent: `pi_test_${++count}` }),
95
+ /** The person pays by bank: the session completes unpaid until the payment clears. */
96
+ clearing: (id) => change(id, { status: "complete", payment_status: "unpaid", payment_intent: `pi_test_${++count}` }),
97
+ /** A bank payment clears. */
98
+ cleared: (id) => change(id, { payment_status: "paid" }),
99
+ /** Nobody paid before the page closed. */
100
+ expire: (id) => change(id, { status: "expired" }),
101
+ /**
102
+ * One of Stripe's events about a session, signed as Stripe signs it.
103
+ * @param {string} type
104
+ * @param {Record<string, any>} session
105
+ */
106
+ event(type, session, id = `evt_test_${++count}`) {
107
+ const rawBody = Buffer.from(JSON.stringify({ id, object: "event", type, livemode: false, data: { object: { ...session } } }));
108
+ return { rawBody, signature: signer.webhooks.generateTestHeaderString({ payload: rawBody.toString(), secret: webhookSecret }) };
109
+ },
110
+ close: () => new Promise((resolve) => server.close(resolve))
111
+ };
112
+ }
@@ -0,0 +1,11 @@
1
+ import initial from "../../migrations/payments_core_initial.cjs";
2
+ import topUps from "../../migrations/payments_core_top_ups.cjs";
3
+
4
+ /**
5
+ * Runs the package's migrations in the order Knex sorts them: the payment tables, then the top-ups table.
6
+ * @param {import("knex").Knex} knex
7
+ */
8
+ export async function migratePayments(knex) {
9
+ await initial.up(knex);
10
+ await topUps.up(knex);
11
+ }
@@ -0,0 +1,85 @@
1
+ import { createPaymentCheckoutService } from "../../src/server/checkout.js";
2
+ import { createStripePaymentAdapter } from "../../src/server/stripe.js";
3
+ import { migratePayments } from "./migrations.js";
4
+ import { createTestPaymentStore } from "./paymentStore.js";
5
+
6
+ // An application that takes top-ups, as one composes them: the payment store on its own database, the Stripe adapter
7
+ // on the real Stripe SDK talking to a stand-in for Stripe's API (fakeStripe.js), and its checkout service with a
8
+ // credit function that writes each credit as a row of its own balance table, in the transaction that settles the
9
+ // top-up. The balance table has no unique reference on purpose, so a top-up credited twice shows as two rows.
10
+
11
+ const OFFER = Object.freeze({ name: "Credits", currency: "USD", minimumAmount: 100, maximumAmount: 50000 });
12
+ const RETURN_URL = "https://app.example/credits";
13
+
14
+ /** The balance table the test application keeps, in the database the payment tables are in. */
15
+ async function createBalanceTable(knex) {
16
+ await knex.schema.createTable("test_credits", (table) => {
17
+ table.increments("id");
18
+ table.string("reference", 200).notNullable();
19
+ table.string("subject_id", 200).notNullable();
20
+ table.integer("amount").notNullable();
21
+ table.string("currency", 3).notNullable();
22
+ });
23
+ }
24
+
25
+ /**
26
+ * @param {import("knex").Knex} knex A database of the test's own, not yet migrated.
27
+ * @param {Awaited<ReturnType<typeof import("./fakeStripe.js").startFakeStripe>>} stripe
28
+ * @param {{ credit?: Function, appEnv?: string, topUps?: object | undefined }} [options] `credit` replaces the
29
+ * application's credit (it gets the default's arguments and the default itself); `topUps: undefined` composes none.
30
+ */
31
+ export async function createTopUpApp(knex, stripe, { credit, appEnv = "test", ...options } = {}) {
32
+ await migratePayments(knex);
33
+ await createBalanceTable(knex);
34
+ const store = await createTestPaymentStore(knex);
35
+ const authorizations = [];
36
+ const writeCredit = async ({ reference, subjectId, amount, currency }, txOptions) => {
37
+ await txOptions.trx("test_credits").insert({ reference, subject_id: subjectId, amount, currency });
38
+ };
39
+ const adapter = createStripePaymentAdapter({
40
+ apiKey: stripe.secretKey,
41
+ appEnv,
42
+ apiBaseUrl: stripe.url,
43
+ webhookSecret: stripe.webhookSecret,
44
+ environment: "sandbox",
45
+ providerAccountId: stripe.accountId,
46
+ priceBindings: {}
47
+ });
48
+ const merchantScope = { applicationId: "app", integrationId: "billing", providerAccountId: stripe.accountId, environment: "sandbox" };
49
+ const service = createPaymentCheckoutService({
50
+ appEnv,
51
+ adapter,
52
+ store,
53
+ payments: {
54
+ inspect: async () => ({ balance: 0, features: [], subscriptions: [] }),
55
+ reconcileEvent: async () => {
56
+ throw new Error("a top-up's event reached subscription handling");
57
+ }
58
+ },
59
+ merchantScope,
60
+ returnUrl: RETURN_URL,
61
+ authorize: async (actor, request) => {
62
+ authorizations.push(request);
63
+ return actor === request.subjectId;
64
+ },
65
+ ...(Object.hasOwn(options, "topUps") ? { topUps: options.topUps } : {
66
+ topUps: { offer: OFFER, credit: credit ? (request, txOptions) => credit(request, txOptions, writeCredit) : writeCredit }
67
+ })
68
+ });
69
+ const session = (topUpId) => [...stripe.sessions.values()].find((each) => each.client_reference_id === topUpId);
70
+ return {
71
+ service,
72
+ store,
73
+ merchantScope,
74
+ authorizations,
75
+ /** The credit rows of a subject's balance, in the order they were written. */
76
+ credits: async (subjectId) => (await knex("test_credits").where({ subject_id: subjectId }).orderBy("id"))
77
+ .map(({ reference, amount, currency }) => ({ reference, amount, currency })),
78
+ /** The session Stripe holds for a top-up. */
79
+ session,
80
+ /** Stripe's event about a top-up's session as it now stands, signed, as the webhook route passes it on. */
81
+ event: (type, topUpId, changes = {}) => stripe.event(type, { ...session(topUpId), ...changes })
82
+ };
83
+ }
84
+
85
+ export { OFFER, RETURN_URL };