@ultimabase/stripe 0.8.0-canary.20261114123635 → 1.0.0

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/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ultimabase/stripe
2
2
 
3
- ## 0.8.0-canary.20261114123635
3
+ ## 1.0.0
4
4
 
5
5
  ### Minor Changes
6
6
 
@@ -41,12 +41,15 @@
41
41
  'refundAndCancel'` refunds the payment Radar warns of, once, and `dispute: 'cancel'` leaves a
42
42
  disputed payment to its dispute; both end the payer's live subscriptions at once, without
43
43
  proration, and log a warning. The fake's `warnFraud` and `openDispute` put a test's payment at risk.
44
+ - a7127c3: `@ultimabase/stripe/sandbox` runs an application's tests against a Stripe sandbox (D-401): `stripeSandbox({ secret, webhook })` gives payers customers on test clocks, moves those clocks with `advance`, posts the run's customers' events to the webhook with `deliver`, checks the catalog with `expectCatalog`, and deletes what the run made with `cleanup`.
44
45
  - e289391: `stripe.checkout`'s `terms.acceptance` takes texts by locale, such as
45
46
  `{ default: '…', fr: '…', 'pt-BR': '…' }`: the Checkout page's language picks one, then its language
46
47
  part, then `default` (D-390). A key that is not a canonical locale is refused.
47
48
 
48
49
  ### Patch Changes
49
50
 
51
+ - 4b2278d: `stripePlugin`, its `keys` and `applyStripeCatalog` refuse an option misspelt `key` without quoting
52
+ its value, which may be a secret key: `stripePlugin takes no key.`
50
53
  - 01f2c61: A subscription's row no longer keeps `scheduledProduct`, `scheduledPrice` and `scheduledAt` once the
51
54
  scheduled phase has begun at Stripe: the next phase is read after the one Stripe says is current,
52
55
  in Stripe's time, which a test clock moves, rather than by the server's clock.
@@ -55,13 +58,32 @@
55
58
  - Updated dependencies [94145f9]
56
59
  - Updated dependencies [8f82820]
57
60
  - Updated dependencies [1b9515a]
61
+ - Updated dependencies [4b2278d]
58
62
  - Updated dependencies [458361b]
59
63
  - Updated dependencies [4c9e506]
64
+ - Updated dependencies [4b2278d]
65
+ - Updated dependencies [4b2278d]
66
+ - Updated dependencies [4b2278d]
67
+ - Updated dependencies [4b2278d]
68
+ - Updated dependencies [4b2278d]
60
69
  - Updated dependencies [20aec1b]
70
+ - Updated dependencies [4b2278d]
71
+ - Updated dependencies [4b2278d]
72
+ - Updated dependencies [4b2278d]
73
+ - Updated dependencies [4b2278d]
61
74
  - Updated dependencies [51f8f04]
75
+ - Updated dependencies [4b2278d]
76
+ - Updated dependencies [4b2278d]
62
77
  - Updated dependencies [3099475]
78
+ - Updated dependencies [fd85be5]
63
79
  - Updated dependencies [81f66fb]
80
+ - Updated dependencies [4b2278d]
81
+ - Updated dependencies [4b2278d]
82
+ - Updated dependencies [4b2278d]
64
83
  - Updated dependencies [1520a09]
65
- - ultimabase@0.8.0-canary.20261114123635
66
- - @ultimabase/http@0.8.0-canary.20261114123635
67
- - @ultimabase/jobs@0.8.0-canary.20261114123635
84
+ - Updated dependencies [4b2278d]
85
+ - Updated dependencies [4b2278d]
86
+ - ultimabase@1.0.0
87
+ - @ultimabase/http@1.0.0
88
+ - @ultimabase/jobs@1.0.0
89
+ - @ultimabase/testing@1.0.0
@@ -1 +1 @@
1
- {"version":3,"file":"calls.d.ts","sourceRoot":"","sources":["../src/calls.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAGhE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAIxC,KAAK,KAAK,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AACpC,uDAAuD;AACvD,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CA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C,QAAQ,CAAC,KAAK,EAAE,OAAO,KAAK,CAAA;IAC5B,QAAQ,CAAC,KAAK,EAAE,OAAO,KAAK,CAAA;IAC5B,QAAQ,CAAC,OAAO,EAAE,OAAO,OAAO,CAAA;CAC4B,CAAA"}
package/dist/calls.js CHANGED
@@ -49,8 +49,8 @@ function billingOf(running, product) {
49
49
  throw new Error(`${product.key} needs a model definePurchase returned, to record its payments.`);
50
50
  }
51
51
  /**
52
- * Runs `run` with the payer's customer at Stripe, under its lock, after
53
- * expiring its open Checkouts; a customer deleted at Stripe is created again.
52
+ * Runs `run` with the payer's customer at Stripe, under its lock; a customer
53
+ * deleted at Stripe is created again.
54
54
  */
55
55
  async function withCustomer(billing, payer, run) {
56
56
  const { gateway } = stripeOf('stripe');
@@ -60,7 +60,6 @@ async function withCustomer(billing, payer, run) {
60
60
  const attempt = async (current) => {
61
61
  const { row: saved, stripeId, profile, } = await ensureCustomer(current, read);
62
62
  try {
63
- await gateway.expireCheckouts(stripeId);
64
63
  return await run(gateway, stripeId, profile.locale ?? null);
65
64
  }
66
65
  catch (error) {
@@ -111,6 +110,7 @@ export async function checkout(args) {
111
110
  const subscribing = 'prices' in product;
112
111
  const model = billingOf(running, product);
113
112
  return withCustomer(model, args.payer, async (gateway, customerId, locale) => {
113
+ await gateway.expireCheckouts(customerId);
114
114
  const trial = args.trialDays ?? (await firstTrial(model, args.payer, product, key));
115
115
  if (subscribing && running.oneSubscription) {
116
116
  const { subscriptions } = await gateway.readCustomer(customerId);
@@ -190,7 +190,8 @@ export async function portal(args) {
190
190
  throw new Error('stripe.portal needs a model defineSubscription returned.');
191
191
  }
192
192
  const flow = await flowOf(running, model, args);
193
- running.portal ??= (await gateway.readCatalog()).portal?.id ?? null;
193
+ if (running.portal === undefined)
194
+ running.portal = (await gateway.readCatalog()).portal?.id ?? null;
194
195
  const configuration = running.portal;
195
196
  const returnUrl = args.returnUrl ?? running.catalog.portal.returnUrl;
196
197
  return withCustomer(model, args.payer, async (_, customerId, locale) => gateway.openPortal({ customerId, configuration, returnUrl, flow, locale }));
@@ -18,8 +18,8 @@ export declare function profileOf(payer: object): CustomerProfile;
18
18
  export declare function renewed(row: Customer): Promise<Customer>;
19
19
  /**
20
20
  * The payer's customer at Stripe, under its lock: created once, with an
21
- * idempotency key, and given the payer's profile when it changed. A customer
22
- * deleted at Stripe gives the payer a new row, so a new key.
21
+ * idempotency key per row and profile, and given the payer's profile when it
22
+ * changed. A customer deleted at Stripe gives the payer a new row.
23
23
  */
24
24
  export declare function ensureCustomer(row: Customer, payer: Row): Promise<{
25
25
  readonly row: Customer;
@@ -1 +1 @@
1
- {"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../src/customer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAE1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAE3D,OAAO,EAAK,cAAc,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAGhD,MAAM,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,cAAc,CAAC,CAAA;AAEtD,kEAAkE;AAClE,wBAAsB,QAAQ,CAC7B,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,EACvB,EAAE,EAAE,MAAM,GACR,OAAO,CAAC,GAAG,CAAC,CAMd;AAED,0DAA0D;AAC1D,wBAAsB,WAAW,CAChC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CAanB;AAED;;;GAGG;AACH,wBAAsB,MAAM,CAAC,CAAC,EAC7B,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,GAChC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CASxB;AAED,kEAAkE;AAClE,wBAAgB,SAAS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gB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,eAAe,CAYxD;AAED,uEAAuE;AACvE,wBAAsB,OAAO,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CACnC,GAAG,EAAE,QAAQ,EACb,KAAK,EAAE,GAAG,GACR,OAAO,CAAC;IACV,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAA;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAA;CACjC,CAAC,CAsBD"}
package/dist/customer.js CHANGED
@@ -1,3 +1,7 @@
1
+ // A payer's Stripe customer (D-373 point 3): one row per payer in
2
+ // `StripeCustomer`, whose update is the lock every write about the payer
3
+ // takes, and one customer at Stripe, created once.
4
+ import { hash } from 'node:crypto';
1
5
  import { PublicError, transaction } from 'ultimabase';
2
6
  import { Missing } from './billing-gateway.js';
3
7
  import { M, StripeCustomer } from './models.js';
@@ -59,8 +63,8 @@ export async function renewed(row) {
59
63
  }
60
64
  /**
61
65
  * The payer's customer at Stripe, under its lock: created once, with an
62
- * idempotency key, and given the payer's profile when it changed. A customer
63
- * deleted at Stripe gives the payer a new row, so a new key.
66
+ * idempotency key per row and profile, and given the payer's profile when it
67
+ * changed. A customer deleted at Stripe gives the payer a new row.
64
68
  */
65
69
  export async function ensureCustomer(row, payer) {
66
70
  const { gateway } = stripeOf('stripe');
@@ -81,7 +85,9 @@ export async function ensureCustomer(row, payer) {
81
85
  await StripeCustomer.update({ where: { id: row.id }, data }, M);
82
86
  return { row, stripeId: row.stripeId, profile };
83
87
  }
84
- const stripeId = await gateway.createCustomer(profile, `customer-${row.id}`);
88
+ // A rolled back creation leaves its key used, with the profile it sent.
89
+ const key = hash('sha256', row.id + json, 'base64url');
90
+ const stripeId = await gateway.createCustomer(profile, `customer-${key}`);
85
91
  const data = { stripeId, profile: json };
86
92
  await StripeCustomer.update({ where: { id: row.id }, data }, M);
87
93
  return { row, stripeId, profile };
@@ -1 +1 @@
1
- {"version":3,"file":"fake-billing.d.ts","sourceRoot":"","sources":["../src/fake-billing.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACX,cAAc,EACd,aAAa,EACb,eAAe,EACf,eAAe,EACf,WAAW,EACX,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,MAAM,sBAAsB,CAAA;AAG7B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAE/C,sCAAsC;AACtC,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAA;IACjC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;IACzB,2DAA2D;IAC3D,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAC5B;AAED,sCAAsC;AACtC,MAAM,WAAW,YAAa,SAAQ,aAAa;IAClD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAA;CAChD;AAED,iFAAiF;AACjF,MAAM,WAAW,WAAY,SAAQ,SAAS;IAC7C,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IAC7C,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IAC7C,QAAQ,CAAC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;IACvD,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CA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,CAAC,EACxC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAC/B;IACF,QAAQ,CAAC,OAAO,EAAE,cAAc,GAAG,eAAe,CAAA;IAClD,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAA;CAC1B,CAoRA"}
@@ -18,6 +18,7 @@ const periodOf = ({ every, everyCount }) => (days[every] ?? 30) * everyCount * d
18
18
  /** The fake's billing, over its catalog's prices. */
19
19
  export function fakeBilling(prices, newId) {
20
20
  const customers = new Map();
21
+ // Like Stripe's: a key gives its first answer to the same parameters only.
21
22
  const keys = new Map();
22
23
  const checkouts = new Map();
23
24
  const subscriptions = new Map();
@@ -128,12 +129,15 @@ export function fakeBilling(prices, newId) {
128
129
  };
129
130
  const gateway = {
130
131
  createCustomer: async (profile, idempotencyKey) => {
132
+ const params = JSON.stringify(profile);
131
133
  const held = keys.get(idempotencyKey);
134
+ if (held?.[1] === params)
135
+ return held[0];
132
136
  if (held !== undefined)
133
- return held;
137
+ throw new Error('idempotency_error');
134
138
  const id = newId('cus');
135
139
  customers.set(id, { id, profile, deleted: false, card: null });
136
- keys.set(idempotencyKey, id);
140
+ keys.set(idempotencyKey, [id, params]);
137
141
  return id;
138
142
  },
139
143
  updateCustomer: async (id, profile) => {
package/dist/jobs.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { Job, RecurringJob } from '@ultimabase/jobs';
2
2
  /**
3
- * Acts on a payment at risk (D-388), syncs the customer a stored event is
4
- * about, then marks it processed.
3
+ * Acts on a payment at risk (D-388), enqueues the sync of the customer a
4
+ * stored event is about, then marks it processed. The sync's key merges the
5
+ * events of one customer that arrive together into one waiting run, which
6
+ * begins after them all (D-365).
5
7
  */
6
8
  export declare const eventJob: Job<'stripe.event', {
7
9
  readonly event: string;
@@ -1 +1 @@
1
- {"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAkCzD;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,GAAG,CAAC,cAAc,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CA6BlE,CAAA;AAYH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,GAAG,CACzB,cAAc,EACd;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAsBjD,CAAA;AAgHF,wCAAwC;AACxC,eAAO,MAAM,UAAU,EAAE,SAAS,CACjC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,MAAM,CAAC,CACzC,EAQA,CAAA"}
1
+ {"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AA6CzD;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,EAAE,GAAG,CAAC,cAAc,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CA+BlE,CAAA;AAEH;;;GAGG;AACH,eAAO,MAAM,QAAQ,EAAE,GAAG,CACzB,cAAc,EACd;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAsBjD,CAAA;AAgHF,wCAAwC;AACxC,eAAO,MAAM,UAAU,EAAE,SAAS,CACjC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,YAAY,CAAC,MAAM,CAAC,CACzC,EAQA,CAAA"}
package/dist/jobs.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { defineJob } from '@ultimabase/jobs';
2
+ import { transaction } from 'ultimabase';
2
3
  import { auditJob } from './audit.js';
3
4
  import { locked } from './customer.js';
4
5
  import { strings } from './job-input.js';
@@ -26,9 +27,20 @@ const overlap = 10 * minute;
26
27
  * margin covers the clocks' gap.
27
28
  */
28
29
  const margin = minute;
30
+ /** Syncs one customer: an event's, or one the reconciliation found stale. */
31
+ const syncJob = defineJob({
32
+ name: 'stripe.sync',
33
+ input: strings('customer'),
34
+ key: ({ customer }) => customer,
35
+ run: async ({ input }) => {
36
+ await syncCustomer(input.customer);
37
+ },
38
+ });
29
39
  /**
30
- * Acts on a payment at risk (D-388), syncs the customer a stored event is
31
- * about, then marks it processed.
40
+ * Acts on a payment at risk (D-388), enqueues the sync of the customer a
41
+ * stored event is about, then marks it processed. The sync's key merges the
42
+ * events of one customer that arrive together into one waiting run, which
43
+ * begins after them all (D-365).
32
44
  */
33
45
  export const eventJob = defineJob({
34
46
  name: 'stripe.event',
@@ -44,22 +56,16 @@ export const eventJob = defineJob({
44
56
  const row = customerId === null
45
57
  ? null
46
58
  : await StripeCustomer.findUnique({ where }, M);
47
- // Synced here: the event stays waiting, so retried, until it is.
48
59
  if (customerId !== null && row !== null) {
49
60
  await settleRisk(event, customerId, logger);
50
- await syncCustomer(row.id);
51
61
  }
52
- const data = { processedAt: new Date() };
53
- await StripeEvent.update({ where: { id: event.id }, data }, M);
54
- },
55
- });
56
- /** Syncs one customer, which the reconciliation found stale. */
57
- const syncJob = defineJob({
58
- name: 'stripe.sync',
59
- input: strings('customer'),
60
- key: ({ customer }) => customer,
61
- run: async ({ input }) => {
62
- await syncCustomer(input.customer);
62
+ // A customer with no row yet is synced by the hourly scan.
63
+ await transaction(async () => {
64
+ if (row !== null)
65
+ await syncJob.enqueue({ customer: row.id });
66
+ const data = { processedAt: new Date() };
67
+ await StripeEvent.update({ where: { id: event.id }, data }, M);
68
+ });
63
69
  },
64
70
  });
65
71
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAOA,wEAAwE;AACxE,eAAO,MAAM,OAAO,UAAW,MAAM,cAAc,MAAM,KAAG,MAG3D,CAAA;AAED;;;GAGG;AACH,wBAAgB,OAAO,CACtB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,OAAO,EACnB,IAAI,EAAE,SAAS,MAAM,EAAE,GACrB,OAAO,CAAC,UAAU,IAAI,MAAM,CAS9B;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,CAM1D"}
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAOA,wEAAwE;AACxE,eAAO,MAAM,OAAO,UAAW,MAAM,cAAc,MAAM,KAAG,MAG3D,CAAA;AAED;;;GAGG;AACH,wBAAgB,OAAO,CACtB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,OAAO,EACnB,IAAI,EAAE,SAAS,MAAM,EAAE,GACrB,OAAO,CAAC,UAAU,IAAI,MAAM,CAY9B;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,CAM1D"}
package/dist/keys.js CHANGED
@@ -16,9 +16,12 @@ export function ownKeys(entry, definition, keys) {
16
16
  if (typeof definition !== 'object' || definition === null) {
17
17
  throw new Refused(`${entry} takes an object.`);
18
18
  }
19
+ // Only a definition that takes a key is named by it: an option misspelt
20
+ // `key` may hold a secret key, never quoted.
21
+ const where = keys.includes('key') ? whereOf(entry, definition) : entry;
19
22
  for (const key of Object.keys(definition)) {
20
23
  if (!keys.includes(key)) {
21
- throw new Refused(`${whereOf(entry, definition)} takes no ${key}.`);
24
+ throw new Refused(`${where} takes no ${key}.`);
22
25
  }
23
26
  }
24
27
  }
@@ -0,0 +1,66 @@
1
+ import type { Stripe } from 'stripe';
2
+ import { type StripeCatalogOptions } from './apply.ts';
3
+ /** What `stripeSandbox` takes. */
4
+ export interface SandboxOptions {
5
+ /** The sandbox's secret key, sk_test_…; `undefined` is refused, as an unset variable. */
6
+ readonly secret: string | undefined;
7
+ /** The webhook secret of the application's `stripePlugin`, which signs what `deliver` posts. */
8
+ readonly webhook: string;
9
+ }
10
+ /** The catalog `expectCatalog` compares: `applyStripeCatalog`'s, without its key. */
11
+ export type SandboxCatalog = Omit<StripeCatalogOptions, 'secret' | 'dryRun'>;
12
+ /** What `payer` makes at Stripe. */
13
+ export interface SandboxPayer {
14
+ readonly customer: string;
15
+ /** The test clock the customer sits on, which `advance` moves. */
16
+ readonly clock: string;
17
+ /** The card the customer pays with by default. */
18
+ readonly method: string;
19
+ }
20
+ /** A Stripe sandbox, and what a test does there. */
21
+ export interface StripeSandbox {
22
+ /** Stripe's client, on the sandbox. */
23
+ readonly client: Stripe;
24
+ /** This run's name, `ub_<time>_<random>`, in what it makes at Stripe. */
25
+ readonly run: string;
26
+ /** An address of this run, `<run>-<name>@example.com`, deleted by `cleanup`. */
27
+ email(name: string): string;
28
+ /** The one customer of `email`, which Checkout made; `deliver` posts its events. */
29
+ customerOf(email: string): Promise<string>;
30
+ /** Gives the customer a card, `pm_card_visa` by default, it pays with by default. */
31
+ payWith(customer: string, card?: string): Promise<string>;
32
+ /** A price's id, by its lookup key: `pro.monthly`. */
33
+ priceId(lookupKey: string): Promise<string>;
34
+ /** Throws the changes the sandbox needs to match the catalog, if any. */
35
+ expectCatalog(options: SandboxCatalog): Promise<void>;
36
+ /**
37
+ * A customer for the payer row `id` of `model`, on a test clock of its
38
+ * own, with a card that pays: the plugin uses it as the one it would make.
39
+ */
40
+ payer(options: {
41
+ readonly model: {
42
+ readonly name: string;
43
+ };
44
+ readonly id: string;
45
+ readonly email?: string;
46
+ readonly card?: string;
47
+ }): Promise<SandboxPayer>;
48
+ /** Moves a test clock `days` ahead, once Stripe ran what that time does. */
49
+ advance(clock: string, options: {
50
+ readonly days: number;
51
+ }): Promise<void>;
52
+ /**
53
+ * Posts this run's customers' events, each once, signed, to the webhook
54
+ * of the application at `url`, then runs the jobs. `again`, a customer,
55
+ * posts its events once more, as Stripe does when an answer is lost.
56
+ */
57
+ deliver(url: string, options?: {
58
+ readonly again?: string;
59
+ readonly path?: string;
60
+ }): Promise<void>;
61
+ /** Deletes this run's test clocks, and the customers of its addresses. */
62
+ cleanup(): Promise<void>;
63
+ }
64
+ /** A Stripe sandbox for tests that run against it. */
65
+ export declare function stripeSandbox(options: SandboxOptions): StripeSandbox;
66
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAGpC,OAAO,EAAE,KAAK,oBAAoB,EAAa,MAAM,YAAY,CAAA;AAUjE,kCAAkC;AAClC,MAAM,WAAW,cAAc;IAC9B,yFAAyF;IACzF,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IACnC,gGAAgG;IAChG,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACxB;AAED,qFAAqF;AACrF,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,oBAAoB,EAAE,QAAQ,GAAG,QAAQ,CAAC,CAAA;AAE5E,oCAAoC;AACpC,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,kEAAkE;IAClE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,kDAAkD;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACvB;AAED,oDAAoD;AACpD,MAAM,WAAW,aAAa;IAC7B,uCAAuC;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,yEAAyE;IACzE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,gFAAgF;IAChF,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;IAC3B,oFAAoF;IACpF,UAAU,CAAC,KAAK,EAAE,M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+ // on against a Stripe sandbox, as UltimaBase's nightly suite does: payers on
3
+ // test clocks, the run's events posted signed to the webhook, the catalog
4
+ // checked against the code, and what the run made deleted at the end.
5
+ import { randomBytes } from 'node:crypto';
6
+ import { runJobs } from '@ultimabase/testing';
7
+ import { Refused } from 'ultimabase';
8
+ import { gatewayOf } from './accounts.js';
9
+ import { catalogOf } from './apply.js';
10
+ import { planCatalog } from './catalog.js';
11
+ import { describeStep } from './describe.js';
12
+ import { postEvent, thinEvent } from './fake-events.js';
13
+ import { managedBy, stripeClient } from './gateway.js';
14
+ import { ownKeys } from './keys.js';
15
+ import { M, StripeCustomer } from './models.js';
16
+ import { ownerOf } from './sdk-billing.js';
17
+ import { refOf } from './sdk-common.js';
18
+ const entry = 'stripeSandbox';
19
+ const day = 24 * 60 * 60;
20
+ /** The sandbox's key, or an error that says what to give. */
21
+ function sandboxKey(secret) {
22
+ if (typeof secret !== 'string' || secret === '') {
23
+ throw new Refused(`${entry}: secret is the secret key of a Stripe sandbox, sk_test_…: set it in the environment that runs these tests.`);
24
+ }
25
+ if (!secret.startsWith('sk_test_')) {
26
+ throw new Refused(`${entry} runs on a sandbox only: secret is a test secret key, sk_test_….`);
27
+ }
28
+ return secret;
29
+ }
30
+ /** A string field of an object Stripe sent, or `undefined`. */
31
+ const read = (object, key) => {
32
+ const value = Reflect.get(Object(object), key);
33
+ return typeof value === 'string' ? value : undefined;
34
+ };
35
+ /** Whether a Stripe call failed because the object is gone. */
36
+ const missing = (error) => Reflect.get(Object(error), 'code') === 'resource_missing';
37
+ /** A Stripe sandbox for tests that run against it. */
38
+ export function stripeSandbox(options) {
39
+ ownKeys(entry, options, ['secret', 'webhook']);
40
+ const secret = sandboxKey(options.secret);
41
+ const { webhook } = options;
42
+ if (typeof webhook !== 'string' || webhook === '') {
43
+ throw new Refused(`${entry}: webhook is the webhook secret of the application's stripePlugin.`);
44
+ }
45
+ const client = stripeClient(secret);
46
+ const run = `ub_${Date.now().toString(36)}_${randomBytes(3).toString('hex')}`;
47
+ // A minute early: a test clock's first events may predate the run's start.
48
+ const began = Math.floor(Date.now() / 1000) - 60;
49
+ const emails = new Set();
50
+ const customers = new Set();
51
+ const found = new Set();
52
+ const clocks = [];
53
+ const posted = new Set();
54
+ const owners = new Map();
55
+ /** The customer an event's object belongs to, asked once per object. */
56
+ const ownerOfObject = async (object) => {
57
+ const kind = read(object, 'object') ?? '';
58
+ const id = read(object, 'id') ?? '';
59
+ if (kind === 'customer')
60
+ return id;
61
+ const customer = Reflect.get(Object(object), 'customer');
62
+ if (typeof customer === 'string')
63
+ return customer;
64
+ const nested = read(customer, 'id');
65
+ if (nested !== undefined)
66
+ return nested;
67
+ // A dispute or a fraud warning names its charge only.
68
+ let owner = owners.get(id);
69
+ if (owner === undefined) {
70
+ owner = ownerOf(client, kind, id).then(refOf);
71
+ owners.set(id, owner);
72
+ }
73
+ return owner;
74
+ };
75
+ const payWith = async (customer, card = 'pm_card_visa') => {
76
+ const { id } = await client.paymentMethods.attach(card, { customer });
77
+ await client.customers.update(customer, {
78
+ invoice_settings: { default_payment_method: id },
79
+ });
80
+ return id;
81
+ };
82
+ return {
83
+ client,
84
+ run,
85
+ email: (name) => {
86
+ const email = `${run}-${name}@example.com`;
87
+ emails.add(email);
88
+ return email;
89
+ },
90
+ customerOf: async (email) => {
91
+ const { data } = await client.customers.list({ email, limit: 2 });
92
+ const [customer] = data;
93
+ if (customer === undefined || data.length > 1) {
94
+ throw new Error(`Stripe holds ${data.length === 0 ? 'no' : 'several'} customers of ${email}: expected one.`);
95
+ }
96
+ customers.add(customer.id);
97
+ found.add(customer.id);
98
+ return customer.id;
99
+ },
100
+ payWith,
101
+ priceId: async (lookupKey) => {
102
+ const { data } = await client.prices.list({
103
+ lookup_keys: [lookupKey],
104
+ active: true,
105
+ limit: 1,
106
+ });
107
+ const [price] = data;
108
+ if (price === undefined) {
109
+ throw new Error(`No active price of the sandbox is ${lookupKey}.`);
110
+ }
111
+ return price.id;
112
+ },
113
+ expectCatalog: async (catalogOptions) => {
114
+ const where = 'expectCatalog';
115
+ ownKeys(where, catalogOptions, [
116
+ 'currency',
117
+ 'taxBehavior',
118
+ 'products',
119
+ 'portal',
120
+ ]);
121
+ const catalog = catalogOf(where, catalogOptions);
122
+ const steps = planCatalog(catalog, await gatewayOf(secret).readCatalog());
123
+ if (steps.length === 0)
124
+ return;
125
+ const lines = steps.map((step) => ` ${describeStep(step, catalog.currency)}`);
126
+ throw new Error([
127
+ `The sandbox's catalog differs from the code, ${String(steps.length)} change${steps.length === 1 ? '' : 's'}:`,
128
+ ...lines,
129
+ 'applyStripeCatalog with the sandbox key applies them.',
130
+ ].join('\n'));
131
+ },
132
+ payer: async ({ model, id, email, card }) => {
133
+ const clock = await client.testHelpers.testClocks.create({
134
+ frozen_time: Math.floor(Date.now() / 1000),
135
+ name: run,
136
+ });
137
+ clocks.push(clock.id);
138
+ const { id: customer } = await client.customers.create({
139
+ ...(email === undefined ? {} : { email }),
140
+ test_clock: clock.id,
141
+ metadata: { managedBy },
142
+ });
143
+ customers.add(customer);
144
+ const method = await payWith(customer, card);
145
+ await StripeCustomer.create({ data: { model: model.name, payer: id, stripeId: customer } }, M);
146
+ return { customer, clock: clock.id, method };
147
+ },
148
+ advance: async (clock, { days }) => {
149
+ if (typeof days !== 'number' || !(days > 0)) {
150
+ throw new Refused('advance: days is a positive number.');
151
+ }
152
+ const testClocks = client.testHelpers.testClocks;
153
+ const { frozen_time: now } = await testClocks.retrieve(clock);
154
+ await testClocks.advance(clock, {
155
+ frozen_time: now + Math.round(days * day),
156
+ });
157
+ for (let tries = 0; tries < 90; tries += 1) {
158
+ const { status } = await testClocks.retrieve(clock);
159
+ if (status === 'ready')
160
+ return;
161
+ if (status === 'internal_failure') {
162
+ throw new Error(`The test clock ${clock} failed at Stripe.`);
163
+ }
164
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
165
+ }
166
+ throw new Error(`The test clock ${clock} took more than 3 minutes.`);
167
+ },
168
+ deliver: async (url, { again, path } = {}) => {
169
+ const created = { gte: began };
170
+ for await (const event of client.events.list({ created, limit: 100 })) {
171
+ const seen = posted.has(event.id);
172
+ const object = event.data.object;
173
+ const owner = await ownerOfObject(object);
174
+ if (owner === null || !customers.has(owner))
175
+ continue;
176
+ if (seen && owner !== again)
177
+ continue;
178
+ posted.add(event.id);
179
+ const id = read(object, 'id');
180
+ const type = read(object, 'object');
181
+ if (id === undefined || type === undefined)
182
+ continue;
183
+ const payload = thinEvent({
184
+ id: event.id,
185
+ type: event.type,
186
+ object: { id, type },
187
+ });
188
+ const response = await postEvent(url, payload, {
189
+ secret: webhook,
190
+ path,
191
+ });
192
+ if (!response.ok) {
193
+ throw new Error(`The webhook answered ${String(response.status)} to ${event.type}.`);
194
+ }
195
+ }
196
+ await runJobs();
197
+ },
198
+ cleanup: async () => {
199
+ // A clock's customers go with it.
200
+ for (const clock of clocks.splice(0)) {
201
+ await client.testHelpers.testClocks.del(clock);
202
+ }
203
+ const ids = new Set(found);
204
+ for (const email of emails) {
205
+ for await (const customer of client.customers.list({ email })) {
206
+ ids.add(customer.id);
207
+ }
208
+ }
209
+ for (const id of ids) {
210
+ try {
211
+ await client.customers.del(id);
212
+ }
213
+ catch (error) {
214
+ if (!missing(error))
215
+ throw error;
216
+ }
217
+ }
218
+ found.clear();
219
+ },
220
+ };
221
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-customer.d.ts","sourceRoot":"","sources":["../src/sdk-customer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACpC,OAAO,KAAK,EACX,aAAa,EAGb,MAAM,sBAAsB,CAAA;AAiH7B,eAAO,MAAM,IAAI,EAAE,aAKlB,CAAA;AAID,wEAAwE;AACxE,wBAAsB,OAAO,CAC5B,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,KAAK,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC3D,OAAO,CAAC,aAAa,CAAC,CAoExB"}
1
+ {"version":3,"file":"sdk-customer.d.ts","sourceRoot":"","sources":["../src/sdk-customer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACpC,OAAO,KAAK,EACX,aAAa,EAGb,MAAM,sBAAsB,CAAA;AAiH7B,eAAO,MAAM,IAAI,EAAE,aAKlB,CAAA;AAID,wEAAwE;AACxE,wBAAsB,OAAO,CAC5B,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,KAAK,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC3D,OAAO,CAAC,aAAa,CAAC,CAsExB"}
@@ -100,7 +100,8 @@ export async function stateOf(client, id, asked) {
100
100
  const customer = await client.customers.retrieve(id);
101
101
  if (customer.deleted === true)
102
102
  return gone;
103
- // A refund comes within the year; a paid period, within its own.
103
+ // A refund or a dispute comes within the year; a paid period, within its
104
+ // own. An older payment keeps the state it was last synced with.
104
105
  const created = { gte: Math.floor(Date.now() / 1000) - 400 * day };
105
106
  const [subscriptions, intents, invoices, sessions] = await Promise.all([
106
107
  all(client.subscriptions.list({
@@ -111,6 +112,7 @@ export async function stateOf(client, id, asked) {
111
112
  })),
112
113
  all(client.paymentIntents.list({
113
114
  customer: id,
115
+ created,
114
116
  limit: 100,
115
117
  expand: ['data.latest_charge'],
116
118
  })),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimabase/stripe",
3
- "version": "0.8.0-canary.20261114123635",
3
+ "version": "1.0.0",
4
4
  "description": "Stripe for UltimaBase: a catalog declared in code, sold on Stripe's Checkout, with subscriptions, purchases and credits kept in the application's models.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -15,6 +15,7 @@
15
15
  },
16
16
  "exports": {
17
17
  ".": "./dist/index.js",
18
+ "./sandbox": "./dist/sandbox.js",
18
19
  "./testing": "./dist/testing.js"
19
20
  },
20
21
  "files": [
@@ -29,21 +30,28 @@
29
30
  "publishConfig": {
30
31
  "exports": {
31
32
  ".": "./dist/index.js",
33
+ "./sandbox": "./dist/sandbox.js",
32
34
  "./testing": "./dist/testing.js"
33
35
  }
34
36
  },
35
37
  "peerDependencies": {
36
- "@ultimabase/http": "0.8.0-canary.20261114123635",
37
- "@ultimabase/jobs": "0.8.0-canary.20261114123635",
38
- "ultimabase": "0.8.0-canary.20261114123635"
38
+ "@ultimabase/http": "^1.0.0",
39
+ "@ultimabase/jobs": "^1.0.0",
40
+ "@ultimabase/testing": "^1.0.0",
41
+ "ultimabase": "^1.0.0"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "@ultimabase/testing": {
45
+ "optional": true
46
+ }
39
47
  },
40
48
  "devDependencies": {
41
- "@ultimabase/graphql": "0.8.0-canary.20261114123635",
42
- "@ultimabase/http": "0.8.0-canary.20261114123635",
43
- "@ultimabase/jobs": "0.8.0-canary.20261114123635",
44
- "@ultimabase/rest": "0.8.0-canary.20261114123635",
45
- "@ultimabase/testing": "0.8.0-canary.20261114123635",
46
- "ultimabase": "0.8.0-canary.20261114123635",
49
+ "@ultimabase/graphql": "1.0.0",
50
+ "@ultimabase/http": "1.0.0",
51
+ "@ultimabase/jobs": "1.0.0",
52
+ "@ultimabase/rest": "1.0.0",
53
+ "@ultimabase/testing": "1.0.0",
54
+ "ultimabase": "1.0.0",
47
55
  "vite": "8.3.4",
48
56
  "vitest": "5.0.5"
49
57
  },
package/src/calls.ts CHANGED
@@ -122,8 +122,8 @@ function billingOf(running: Running, product: Product): Billing {
122
122
  }
123
123
 
124
124
  /**
125
- * Runs `run` with the payer's customer at Stripe, under its lock, after
126
- * expiring its open Checkouts; a customer deleted at Stripe is created again.
125
+ * Runs `run` with the payer's customer at Stripe, under its lock; a customer
126
+ * deleted at Stripe is created again.
127
127
  */
128
128
  async function withCustomer<R>(
129
129
  billing: Billing,
@@ -145,7 +145,6 @@ async function withCustomer<R>(
145
145
  profile,
146
146
  } = await ensureCustomer(current, read)
147
147
  try {
148
- await gateway.expireCheckouts(stripeId)
149
148
  return await run(gateway, stripeId, profile.locale ?? null)
150
149
  } catch (error) {
151
150
  if (!(error instanceof Missing) || current !== row) throw error
@@ -205,6 +204,7 @@ export async function checkout<const P extends Product>(
205
204
  model,
206
205
  args.payer,
207
206
  async (gateway, customerId, locale) => {
207
+ await gateway.expireCheckouts(customerId)
208
208
  const trial =
209
209
  args.trialDays ?? (await firstTrial(model, args.payer, product, key))
210
210
  if (subscribing && running.oneSubscription) {
@@ -307,7 +307,8 @@ export async function portal<const P extends SubscriptionProduct>(
307
307
  throw new Error('stripe.portal needs a model defineSubscription returned.')
308
308
  }
309
309
  const flow = await flowOf(running, model, args)
310
- running.portal ??= (await gateway.readCatalog()).portal?.id ?? null
310
+ if (running.portal === undefined)
311
+ running.portal = (await gateway.readCatalog()).portal?.id ?? null
311
312
  const configuration = running.portal
312
313
  const returnUrl = args.returnUrl ?? running.catalog.portal.returnUrl
313
314
  return withCustomer(model, args.payer, async (_, customerId, locale) =>
package/src/customer.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // A payer's Stripe customer (D-373 point 3): one row per payer in
2
2
  // `StripeCustomer`, whose update is the lock every write about the payer
3
3
  // takes, and one customer at Stripe, created once.
4
+ import { hash } from 'node:crypto'
4
5
  import type { RecordOf } from 'ultimabase'
5
6
  import { PublicError, transaction } from 'ultimabase'
6
7
  import type { CustomerProfile } from './billing-gateway.ts'
@@ -84,8 +85,8 @@ export async function renewed(row: Customer): Promise<Customer> {
84
85
 
85
86
  /**
86
87
  * The payer's customer at Stripe, under its lock: created once, with an
87
- * idempotency key, and given the payer's profile when it changed. A customer
88
- * deleted at Stripe gives the payer a new row, so a new key.
88
+ * idempotency key per row and profile, and given the payer's profile when it
89
+ * changed. A customer deleted at Stripe gives the payer a new row.
89
90
  */
90
91
  export async function ensureCustomer(
91
92
  row: Customer,
@@ -110,7 +111,9 @@ export async function ensureCustomer(
110
111
  await StripeCustomer.update({ where: { id: row.id }, data }, M)
111
112
  return { row, stripeId: row.stripeId, profile }
112
113
  }
113
- const stripeId = await gateway.createCustomer(profile, `customer-${row.id}`)
114
+ // A rolled back creation leaves its key used, with the profile it sent.
115
+ const key = hash('sha256', row.id + json, 'base64url')
116
+ const stripeId = await gateway.createCustomer(profile, `customer-${key}`)
114
117
  const data = { stripeId, profile: json }
115
118
  await StripeCustomer.update({ where: { id: row.id }, data }, M)
116
119
  return { row, stripeId, profile }
@@ -93,7 +93,8 @@ export function fakeBilling(
93
93
  readonly fake: FakeBilling
94
94
  } {
95
95
  const customers = new Map<string, FakeCustomer>()
96
- const keys = new Map<string, string>()
96
+ // Like Stripe's: a key gives its first answer to the same parameters only.
97
+ const keys = new Map<string, readonly [id: string, params: string]>()
97
98
  const checkouts = new Map<string, FakeCheckout>()
98
99
  const subscriptions = new Map<string, StripeSubscription>()
99
100
  const payments = new Map<string, StripePayment>()
@@ -206,11 +207,13 @@ export function fakeBilling(
206
207
  }
207
208
  const gateway: BillingGateway & RecoveryGateway = {
208
209
  createCustomer: async (profile, idempotencyKey) => {
210
+ const params = JSON.stringify(profile)
209
211
  const held = keys.get(idempotencyKey)
210
- if (held !== undefined) return held
212
+ if (held?.[1] === params) return held[0]
213
+ if (held !== undefined) throw new Error('idempotency_error')
211
214
  const id = newId('cus')
212
215
  customers.set(id, { id, profile, deleted: false, card: null })
213
- keys.set(idempotencyKey, id)
216
+ keys.set(idempotencyKey, [id, params])
214
217
  return id
215
218
  },
216
219
  updateCustomer: async (id, profile) => {
package/src/jobs.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // left behind.
5
5
  import type { Job, RecurringJob } from '@ultimabase/jobs'
6
6
  import { defineJob } from '@ultimabase/jobs'
7
+ import { transaction } from 'ultimabase'
7
8
  import { auditJob } from './audit.ts'
8
9
  import type { Customer } from './customer.ts'
9
10
  import { locked } from './customer.ts'
@@ -36,9 +37,21 @@ const overlap = 10 * minute
36
37
  */
37
38
  const margin = minute
38
39
 
40
+ /** Syncs one customer: an event's, or one the reconciliation found stale. */
41
+ const syncJob = defineJob({
42
+ name: 'stripe.sync',
43
+ input: strings('customer'),
44
+ key: ({ customer }) => customer,
45
+ run: async ({ input }) => {
46
+ await syncCustomer(input.customer)
47
+ },
48
+ })
49
+
39
50
  /**
40
- * Acts on a payment at risk (D-388), syncs the customer a stored event is
41
- * about, then marks it processed.
51
+ * Acts on a payment at risk (D-388), enqueues the sync of the customer a
52
+ * stored event is about, then marks it processed. The sync's key merges the
53
+ * events of one customer that arrive together into one waiting run, which
54
+ * begins after them all (D-365).
42
55
  */
43
56
  export const eventJob: Job<'stripe.event', { readonly event: string }> =
44
57
  defineJob({
@@ -61,26 +74,18 @@ export const eventJob: Job<'stripe.event', { readonly event: string }> =
61
74
  customerId === null
62
75
  ? null
63
76
  : await StripeCustomer.findUnique({ where }, M)
64
- // Synced here: the event stays waiting, so retried, until it is.
65
77
  if (customerId !== null && row !== null) {
66
78
  await settleRisk(event, customerId, logger)
67
- await syncCustomer(row.id)
68
79
  }
69
- const data = { processedAt: new Date() }
70
- await StripeEvent.update({ where: { id: event.id }, data }, M)
80
+ // A customer with no row yet is synced by the hourly scan.
81
+ await transaction(async () => {
82
+ if (row !== null) await syncJob.enqueue({ customer: row.id })
83
+ const data = { processedAt: new Date() }
84
+ await StripeEvent.update({ where: { id: event.id }, data }, M)
85
+ })
71
86
  },
72
87
  })
73
88
 
74
- /** Syncs one customer, which the reconciliation found stale. */
75
- const syncJob = defineJob({
76
- name: 'stripe.sync',
77
- input: strings('customer'),
78
- key: ({ customer }) => customer,
79
- run: async ({ input }) => {
80
- await syncCustomer(input.customer)
81
- },
82
- })
83
-
84
89
  /**
85
90
  * Closes the customer of a deleted payer: Stripe deletes it, which ends its
86
91
  * subscriptions, and its row goes. A payer still there keeps it.
package/src/keys.ts CHANGED
@@ -23,9 +23,12 @@ export function ownKeys(
23
23
  if (typeof definition !== 'object' || definition === null) {
24
24
  throw new Refused(`${entry} takes an object.`)
25
25
  }
26
+ // Only a definition that takes a key is named by it: an option misspelt
27
+ // `key` may hold a secret key, never quoted.
28
+ const where = keys.includes('key') ? whereOf(entry, definition) : entry
26
29
  for (const key of Object.keys(definition)) {
27
30
  if (!keys.includes(key)) {
28
- throw new Refused(`${whereOf(entry, definition)} takes no ${key}.`)
31
+ throw new Refused(`${where} takes no ${key}.`)
29
32
  }
30
33
  }
31
34
  }
package/src/sandbox.ts ADDED
@@ -0,0 +1,302 @@
1
+ // @ultimabase/stripe/sandbox (D-401): what an application's own tests run
2
+ // on against a Stripe sandbox, as UltimaBase's nightly suite does: payers on
3
+ // test clocks, the run's events posted signed to the webhook, the catalog
4
+ // checked against the code, and what the run made deleted at the end.
5
+ import { randomBytes } from 'node:crypto'
6
+ import { runJobs } from '@ultimabase/testing'
7
+ import type { Stripe } from 'stripe'
8
+ import { Refused } from 'ultimabase'
9
+ import { gatewayOf } from './accounts.ts'
10
+ import { type StripeCatalogOptions, catalogOf } from './apply.ts'
11
+ import { planCatalog } from './catalog.ts'
12
+ import { describeStep } from './describe.ts'
13
+ import { postEvent, thinEvent } from './fake-events.ts'
14
+ import { managedBy, stripeClient } from './gateway.ts'
15
+ import { ownKeys } from './keys.ts'
16
+ import { M, StripeCustomer } from './models.ts'
17
+ import { ownerOf } from './sdk-billing.ts'
18
+ import { refOf } from './sdk-common.ts'
19
+
20
+ /** What `stripeSandbox` takes. */
21
+ export interface SandboxOptions {
22
+ /** The sandbox's secret key, sk_test_…; `undefined` is refused, as an unset variable. */
23
+ readonly secret: string | undefined
24
+ /** The webhook secret of the application's `stripePlugin`, which signs what `deliver` posts. */
25
+ readonly webhook: string
26
+ }
27
+
28
+ /** The catalog `expectCatalog` compares: `applyStripeCatalog`'s, without its key. */
29
+ export type SandboxCatalog = Omit<StripeCatalogOptions, 'secret' | 'dryRun'>
30
+
31
+ /** What `payer` makes at Stripe. */
32
+ export interface SandboxPayer {
33
+ readonly customer: string
34
+ /** The test clock the customer sits on, which `advance` moves. */
35
+ readonly clock: string
36
+ /** The card the customer pays with by default. */
37
+ readonly method: string
38
+ }
39
+
40
+ /** A Stripe sandbox, and what a test does there. */
41
+ export interface StripeSandbox {
42
+ /** Stripe's client, on the sandbox. */
43
+ readonly client: Stripe
44
+ /** This run's name, `ub_<time>_<random>`, in what it makes at Stripe. */
45
+ readonly run: string
46
+ /** An address of this run, `<run>-<name>@example.com`, deleted by `cleanup`. */
47
+ email(name: string): string
48
+ /** The one customer of `email`, which Checkout made; `deliver` posts its events. */
49
+ customerOf(email: string): Promise<string>
50
+ /** Gives the customer a card, `pm_card_visa` by default, it pays with by default. */
51
+ payWith(customer: string, card?: string): Promise<string>
52
+ /** A price's id, by its lookup key: `pro.monthly`. */
53
+ priceId(lookupKey: string): Promise<string>
54
+ /** Throws the changes the sandbox needs to match the catalog, if any. */
55
+ expectCatalog(options: SandboxCatalog): Promise<void>
56
+ /**
57
+ * A customer for the payer row `id` of `model`, on a test clock of its
58
+ * own, with a card that pays: the plugin uses it as the one it would make.
59
+ */
60
+ payer(options: {
61
+ readonly model: { readonly name: string }
62
+ readonly id: string
63
+ readonly email?: string
64
+ readonly card?: string
65
+ }): Promise<SandboxPayer>
66
+ /** Moves a test clock `days` ahead, once Stripe ran what that time does. */
67
+ advance(clock: string, options: { readonly days: number }): Promise<void>
68
+ /**
69
+ * Posts this run's customers' events, each once, signed, to the webhook
70
+ * of the application at `url`, then runs the jobs. `again`, a customer,
71
+ * posts its events once more, as Stripe does when an answer is lost.
72
+ */
73
+ deliver(
74
+ url: string,
75
+ options?: { readonly again?: string; readonly path?: string },
76
+ ): Promise<void>
77
+ /** Deletes this run's test clocks, and the customers of its addresses. */
78
+ cleanup(): Promise<void>
79
+ }
80
+
81
+ const entry = 'stripeSandbox'
82
+ const day = 24 * 60 * 60
83
+
84
+ /** The sandbox's key, or an error that says what to give. */
85
+ function sandboxKey(secret: unknown): string {
86
+ if (typeof secret !== 'string' || secret === '') {
87
+ throw new Refused(
88
+ `${entry}: secret is the secret key of a Stripe sandbox, sk_test_…: set it in the environment that runs these tests.`,
89
+ )
90
+ }
91
+ if (!secret.startsWith('sk_test_')) {
92
+ throw new Refused(
93
+ `${entry} runs on a sandbox only: secret is a test secret key, sk_test_….`,
94
+ )
95
+ }
96
+ return secret
97
+ }
98
+
99
+ /** A string field of an object Stripe sent, or `undefined`. */
100
+ const read = (object: unknown, key: string): string | undefined => {
101
+ const value: unknown = Reflect.get(Object(object), key)
102
+ return typeof value === 'string' ? value : undefined
103
+ }
104
+
105
+ /** Whether a Stripe call failed because the object is gone. */
106
+ const missing = (error: unknown): boolean =>
107
+ Reflect.get(Object(error), 'code') === 'resource_missing'
108
+
109
+ /** A Stripe sandbox for tests that run against it. */
110
+ export function stripeSandbox(options: SandboxOptions): StripeSandbox {
111
+ ownKeys(entry, options, ['secret', 'webhook'])
112
+ const secret = sandboxKey(options.secret)
113
+ const { webhook } = options
114
+ if (typeof webhook !== 'string' || webhook === '') {
115
+ throw new Refused(
116
+ `${entry}: webhook is the webhook secret of the application's stripePlugin.`,
117
+ )
118
+ }
119
+ const client = stripeClient(secret)
120
+ const run = `ub_${Date.now().toString(36)}_${randomBytes(3).toString('hex')}`
121
+ // A minute early: a test clock's first events may predate the run's start.
122
+ const began = Math.floor(Date.now() / 1000) - 60
123
+ const emails = new Set<string>()
124
+ const customers = new Set<string>()
125
+ const found = new Set<string>()
126
+ const clocks: string[] = []
127
+ const posted = new Set<string>()
128
+ const owners = new Map<string, Promise<string | null>>()
129
+
130
+ /** The customer an event's object belongs to, asked once per object. */
131
+ const ownerOfObject = async (object: unknown): Promise<string | null> => {
132
+ const kind = read(object, 'object') ?? ''
133
+ const id = read(object, 'id') ?? ''
134
+ if (kind === 'customer') return id
135
+ const customer: unknown = Reflect.get(Object(object), 'customer')
136
+ if (typeof customer === 'string') return customer
137
+ const nested = read(customer, 'id')
138
+ if (nested !== undefined) return nested
139
+ // A dispute or a fraud warning names its charge only.
140
+ let owner = owners.get(id)
141
+ if (owner === undefined) {
142
+ owner = ownerOf(client, kind, id).then(refOf)
143
+ owners.set(id, owner)
144
+ }
145
+ return owner
146
+ }
147
+
148
+ const payWith = async (
149
+ customer: string,
150
+ card = 'pm_card_visa',
151
+ ): Promise<string> => {
152
+ const { id } = await client.paymentMethods.attach(card, { customer })
153
+ await client.customers.update(customer, {
154
+ invoice_settings: { default_payment_method: id },
155
+ })
156
+ return id
157
+ }
158
+
159
+ return {
160
+ client,
161
+ run,
162
+ email: (name) => {
163
+ const email = `${run}-${name}@example.com`
164
+ emails.add(email)
165
+ return email
166
+ },
167
+ customerOf: async (email) => {
168
+ const { data } = await client.customers.list({ email, limit: 2 })
169
+ const [customer] = data
170
+ if (customer === undefined || data.length > 1) {
171
+ throw new Error(
172
+ `Stripe holds ${data.length === 0 ? 'no' : 'several'} customers of ${email}: expected one.`,
173
+ )
174
+ }
175
+ customers.add(customer.id)
176
+ found.add(customer.id)
177
+ return customer.id
178
+ },
179
+ payWith,
180
+ priceId: async (lookupKey) => {
181
+ const { data } = await client.prices.list({
182
+ lookup_keys: [lookupKey],
183
+ active: true,
184
+ limit: 1,
185
+ })
186
+ const [price] = data
187
+ if (price === undefined) {
188
+ throw new Error(`No active price of the sandbox is ${lookupKey}.`)
189
+ }
190
+ return price.id
191
+ },
192
+ expectCatalog: async (catalogOptions) => {
193
+ const where = 'expectCatalog'
194
+ ownKeys(where, catalogOptions, [
195
+ 'currency',
196
+ 'taxBehavior',
197
+ 'products',
198
+ 'portal',
199
+ ])
200
+ const catalog = catalogOf(where, catalogOptions)
201
+ const steps = planCatalog(catalog, await gatewayOf(secret).readCatalog())
202
+ if (steps.length === 0) return
203
+ const lines = steps.map(
204
+ (step) => ` ${describeStep(step, catalog.currency)}`,
205
+ )
206
+ throw new Error(
207
+ [
208
+ `The sandbox's catalog differs from the code, ${String(steps.length)} change${steps.length === 1 ? '' : 's'}:`,
209
+ ...lines,
210
+ 'applyStripeCatalog with the sandbox key applies them.',
211
+ ].join('\n'),
212
+ )
213
+ },
214
+ payer: async ({ model, id, email, card }) => {
215
+ const clock = await client.testHelpers.testClocks.create({
216
+ frozen_time: Math.floor(Date.now() / 1000),
217
+ name: run,
218
+ })
219
+ clocks.push(clock.id)
220
+ const { id: customer } = await client.customers.create({
221
+ ...(email === undefined ? {} : { email }),
222
+ test_clock: clock.id,
223
+ metadata: { managedBy },
224
+ })
225
+ customers.add(customer)
226
+ const method = await payWith(customer, card)
227
+ await StripeCustomer.create(
228
+ { data: { model: model.name, payer: id, stripeId: customer } },
229
+ M,
230
+ )
231
+ return { customer, clock: clock.id, method }
232
+ },
233
+ advance: async (clock, { days }) => {
234
+ if (typeof days !== 'number' || !(days > 0)) {
235
+ throw new Refused('advance: days is a positive number.')
236
+ }
237
+ const testClocks = client.testHelpers.testClocks
238
+ const { frozen_time: now } = await testClocks.retrieve(clock)
239
+ await testClocks.advance(clock, {
240
+ frozen_time: now + Math.round(days * day),
241
+ })
242
+ for (let tries = 0; tries < 90; tries += 1) {
243
+ const { status } = await testClocks.retrieve(clock)
244
+ if (status === 'ready') return
245
+ if (status === 'internal_failure') {
246
+ throw new Error(`The test clock ${clock} failed at Stripe.`)
247
+ }
248
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
249
+ }
250
+ throw new Error(`The test clock ${clock} took more than 3 minutes.`)
251
+ },
252
+ deliver: async (url, { again, path } = {}) => {
253
+ const created = { gte: began }
254
+ for await (const event of client.events.list({ created, limit: 100 })) {
255
+ const seen = posted.has(event.id)
256
+ const object: unknown = event.data.object
257
+ const owner = await ownerOfObject(object)
258
+ if (owner === null || !customers.has(owner)) continue
259
+ if (seen && owner !== again) continue
260
+ posted.add(event.id)
261
+ const id = read(object, 'id')
262
+ const type = read(object, 'object')
263
+ if (id === undefined || type === undefined) continue
264
+ const payload = thinEvent({
265
+ id: event.id,
266
+ type: event.type,
267
+ object: { id, type },
268
+ })
269
+ const response = await postEvent(url, payload, {
270
+ secret: webhook,
271
+ path,
272
+ })
273
+ if (!response.ok) {
274
+ throw new Error(
275
+ `The webhook answered ${String(response.status)} to ${event.type}.`,
276
+ )
277
+ }
278
+ }
279
+ await runJobs()
280
+ },
281
+ cleanup: async () => {
282
+ // A clock's customers go with it.
283
+ for (const clock of clocks.splice(0)) {
284
+ await client.testHelpers.testClocks.del(clock)
285
+ }
286
+ const ids = new Set(found)
287
+ for (const email of emails) {
288
+ for await (const customer of client.customers.list({ email })) {
289
+ ids.add(customer.id)
290
+ }
291
+ }
292
+ for (const id of ids) {
293
+ try {
294
+ await client.customers.del(id)
295
+ } catch (error) {
296
+ if (!missing(error)) throw error
297
+ }
298
+ }
299
+ found.clear()
300
+ },
301
+ }
302
+ }
@@ -136,7 +136,8 @@ export async function stateOf(
136
136
  ): Promise<CustomerState> {
137
137
  const customer = await client.customers.retrieve(id)
138
138
  if (customer.deleted === true) return gone
139
- // A refund comes within the year; a paid period, within its own.
139
+ // A refund or a dispute comes within the year; a paid period, within its
140
+ // own. An older payment keeps the state it was last synced with.
140
141
  const created = { gte: Math.floor(Date.now() / 1000) - 400 * day }
141
142
  const [subscriptions, intents, invoices, sessions] = await Promise.all([
142
143
  all(
@@ -150,6 +151,7 @@ export async function stateOf(
150
151
  all(
151
152
  client.paymentIntents.list({
152
153
  customer: id,
154
+ created,
153
155
  limit: 100,
154
156
  expand: ['data.latest_charge'],
155
157
  }),