@molecule/api-resource-payment 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +392 -0
  2. package/package.json +13 -12
package/README.md ADDED
@@ -0,0 +1,392 @@
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-08-04T01:49:17.207Z
7
+ -->
8
+
9
+ # @molecule/api-resource-payment
10
+
11
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
+ > It is written to be read by coding agents as much as by people, and is generated from this
13
+ > package's source — edit `src/index.ts` JSDoc, not this file.
14
+
15
+ Payment resource with subscription plan management.
16
+
17
+ ## Quick Start
18
+
19
+ ```ts
20
+ import { registerPlans, stripeMonthly, stripeYearly } from '@molecule/api-resource-payment'
21
+
22
+ // Register your plan catalogue at startup. The keys are YOUR plan ids; the ready-made
23
+ // Plan objects carry the env-configured Stripe price/product ids (also register the
24
+ // apple and google plan exports when you support those providers):
25
+ registerPlans({ monthly: stripeMonthly, yearly: stripeYearly })
26
+
27
+ // Then grant a plan ONLY after a SERVER-VERIFIED payment — never from a client field.
28
+ // The full verify → record (replay-guarded) → resolve → grant flow lives in the scaffolded
29
+ // user `verifyPayment` handler; verify receipts against @molecule/api-payments and store
30
+ // them with `paymentRecordService.store` (it THROWS on a replayed transactionId — reject).
31
+ ```
32
+
33
+ ## Type
34
+
35
+ `resource`
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ npm install @molecule/api-resource-payment @molecule/api-bond @molecule/api-database @molecule/api-i18n @molecule/api-locales-payment @molecule/api-logger @molecule/api-payments @molecule/api-resource zod
41
+ ```
42
+
43
+ ## API
44
+
45
+ ### Types
46
+
47
+ #### `CreateProps`
48
+
49
+ Fields required when creating a new payment record.
50
+
51
+ ```typescript
52
+ type CreateProps = z.infer<typeof createPropsSchema>
53
+ ```
54
+
55
+ #### `Props`
56
+
57
+ Full payment record properties (userId, platform, transactionId, productId, data, receipt).
58
+
59
+ ```typescript
60
+ type Props = z.infer<typeof propsSchema>
61
+ ```
62
+
63
+ #### `UpdateProps`
64
+
65
+ Updatable payment record fields (data and receipt).
66
+
67
+ ```typescript
68
+ type UpdateProps = z.infer<typeof updatePropsSchema>
69
+ ```
70
+
71
+ ### Classes
72
+
73
+ #### `PaymentRecordConflictError`
74
+
75
+ Error thrown by {@link paymentRecordService.store} when inserting a payment
76
+ record violates the `UNIQUE(platformKey, transactionId)` constraint — i.e. the
77
+ transaction is already bound to an account.
78
+
79
+ This is surfaced (not swallowed) so callers such as the user resource's
80
+ `verifyPayment` handler can enforce first-claim-wins ownership and reject a
81
+ replayed receipt instead of silently granting the plan to a second account.
82
+
83
+ ### Functions
84
+
85
+ #### `getPeriodTime(period)`
86
+
87
+ Get the duration in milliseconds for a billing period.
88
+
89
+ ```typescript
90
+ function getPeriodTime(period: PlanPeriod): number
91
+ ```
92
+
93
+ - `period` — The billing period ('month' or 'year').
94
+
95
+ **Returns:** The period duration in milliseconds.
96
+
97
+ #### `registerPlans(customPlans)`
98
+
99
+ Registers (or replaces) plans in the shared registry consumed by
100
+ `planService` — keyed by `planKey`, merged into the defaults above.
101
+
102
+ The built-in entries carry PLACEHOLDER platform product ids
103
+ (`price_test_id` / `price_prod_id`), so `findPlanByProductId` can never
104
+ match a real platform identifier until the app registers its own catalogue
105
+ — typically derived from its pricing tiers with the real Stripe price ids
106
+ from env (`@molecule/api-bonds-default-express`'s `createBillingRouter`
107
+ does this automatically). Without registration, payment verification and
108
+ webhook plan grants fail with "unknown plan" even though the charge
109
+ succeeded.
110
+
111
+ Idempotent: re-registering the same `planKey` overwrites that entry.
112
+
113
+ ```typescript
114
+ function registerPlans(customPlans: Record<string, Plan>): void
115
+ ```
116
+
117
+ - `customPlans` — Plans to merge into the registry, keyed by `planKey`.
118
+
119
+ ### Constants
120
+
121
+ #### `appleMonthly`
122
+
123
+ Apple App Store monthly subscription plan ($5.99/month, auto-renews).
124
+
125
+ ```typescript
126
+ const appleMonthly: Plan
127
+ ```
128
+
129
+ #### `appleYearly`
130
+
131
+ Apple App Store yearly subscription plan ($64.99/year, auto-renews).
132
+
133
+ ```typescript
134
+ const appleYearly: Plan
135
+ ```
136
+
137
+ #### `createPropsSchema`
138
+
139
+ Zod schema for creating a payment record (picks fields required at creation time).
140
+
141
+ ```typescript
142
+ const createPropsSchema: z.ZodObject<
143
+ {
144
+ createdAt: z.ZodString
145
+ updatedAt: z.ZodString
146
+ userId: z.ZodString
147
+ platformKey: z.ZodDefault<
148
+ z.ZodEnum<{ '': ''; stripe: 'stripe'; apple: 'apple'; google: 'google' }>
149
+ >
150
+ transactionId: z.ZodOptional<z.ZodString>
151
+ productId: z.ZodString
152
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
153
+ receipt: z.ZodOptional<z.ZodString>
154
+ },
155
+ z.core.$strip
156
+ >
157
+ ```
158
+
159
+ #### `googleMonthly`
160
+
161
+ Google Play monthly subscription plan ($5.99/month, auto-renews).
162
+
163
+ ```typescript
164
+ const googleMonthly: Plan
165
+ ```
166
+
167
+ #### `googleYearly`
168
+
169
+ Google Play yearly subscription plan ($64.99/year, auto-renews).
170
+
171
+ ```typescript
172
+ const googleYearly: Plan
173
+ ```
174
+
175
+ #### `i18nRegistered`
176
+
177
+ The i18n registered.
178
+
179
+ ```typescript
180
+ const i18nRegistered: true
181
+ ```
182
+
183
+ #### `paymentRecordService`
184
+
185
+ PaymentRecordService implementation for the bond system.
186
+
187
+ Provides payment record CRUD operations that other resources
188
+ can use through `get<PaymentRecordService>('paymentRecords')`.
189
+
190
+ ```typescript
191
+ const paymentRecordService: PaymentRecordService
192
+ ```
193
+
194
+ #### `plans`
195
+
196
+ All available plans indexed by planKey. The empty string key `''` maps to the default free plan.
197
+
198
+ ```typescript
199
+ const plans: Record<string, Plan>
200
+ ```
201
+
202
+ #### `planService`
203
+
204
+ PlanService implementation for the bond system.
205
+
206
+ Provides plan lookup operations that other resources
207
+ can use through `get('plans')` / `require('plans')`.
208
+
209
+ ```typescript
210
+ const planService: PlanService
211
+ ```
212
+
213
+ #### `propsSchema`
214
+
215
+ Validation schema for props.
216
+
217
+ ```typescript
218
+ const propsSchema: z.ZodObject<
219
+ {
220
+ id: z.ZodString
221
+ createdAt: z.ZodString
222
+ updatedAt: z.ZodString
223
+ userId: z.ZodString
224
+ platformKey: z.ZodDefault<
225
+ z.ZodEnum<{ '': ''; stripe: 'stripe'; apple: 'apple'; google: 'google' }>
226
+ >
227
+ transactionId: z.ZodOptional<z.ZodString>
228
+ productId: z.ZodString
229
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
230
+ receipt: z.ZodOptional<z.ZodString>
231
+ },
232
+ z.core.$strip
233
+ >
234
+ ```
235
+
236
+ #### `resource`
237
+
238
+ Payment resource definition with JSON schema for validation.
239
+
240
+ ```typescript
241
+ const resource: types.Resource
242
+ ```
243
+
244
+ #### `stripeMonthly`
245
+
246
+ Stripe monthly subscription plan ($5/month, auto-renews).
247
+
248
+ ```typescript
249
+ const stripeMonthly: Plan
250
+ ```
251
+
252
+ #### `stripeYearly`
253
+
254
+ Stripe yearly subscription plan ($55/year, auto-renews).
255
+
256
+ ```typescript
257
+ const stripeYearly: Plan
258
+ ```
259
+
260
+ #### `updatePropsSchema`
261
+
262
+ Zod schema for updating a payment record (data and receipt only).
263
+
264
+ ```typescript
265
+ const updatePropsSchema: z.ZodObject<
266
+ {
267
+ data: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>
268
+ receipt: z.ZodOptional<z.ZodOptional<z.ZodString>>
269
+ },
270
+ z.core.$strip
271
+ >
272
+ ```
273
+
274
+ ### Namespaces
275
+
276
+ #### `types`
277
+
278
+ Members:
279
+
280
+ - `types.PlatformKey` — type: Every available platform.
281
+ - `types.PlanAlias` — type: Every available plan alias.
282
+ - `types.PlanPeriod` — type: Every available plan period.
283
+ - `types.Props` — interface: The payment's properties.
284
+ - `types.CreateProps` — type: Properties when creating a payment.
285
+ - `types.UpdateProps` — type: Properties when updating a payment.
286
+ - `types.Plan` — interface: A plan's properties.
287
+ - `types.Resource` — interface: Resource type.
288
+
289
+ ## Services
290
+
291
+ This package exports services that should be registered with the bond system:
292
+
293
+ ```typescript
294
+ import { bond } from '@molecule/api-bond'
295
+ import { planService, paymentRecordService } from '@molecule/api-resource-payment'
296
+
297
+ bond('plans', planService)
298
+ bond('paymentRecords', paymentRecordService)
299
+ ```
300
+
301
+ ## Injection Notes
302
+
303
+ ### Requirements
304
+
305
+ Peer dependencies:
306
+
307
+ - `@molecule/api-bond` ^1.0.1
308
+ - `@molecule/api-database` ^1.0.1
309
+ - `@molecule/api-i18n` ^1.0.1
310
+ - `@molecule/api-locales-payment` ^1.0.1
311
+ - `@molecule/api-logger` ^1.0.1
312
+ - `@molecule/api-payments` ^1.0.1
313
+ - `@molecule/api-resource` ^1.0.1
314
+
315
+ ### Runtime Dependencies
316
+
317
+ - `@molecule/api-bond`
318
+ - `@molecule/api-database`
319
+ - `@molecule/api-i18n`
320
+ - `@molecule/api-locales-payment`
321
+ - `@molecule/api-logger`
322
+ - `@molecule/api-payments`
323
+ - `@molecule/api-resource`
324
+ - `zod`
325
+
326
+ A plan/entitlement is granted ONLY after a SERVER-VERIFIED payment — never from anything
327
+ the client reports. The flow (implemented by the user resource's `verifyPayment` handler):
328
+
329
+ 1. **Verify** the provider token/receipt server-side via the bonded payments provider
330
+ (`@molecule/api-payments` — read its docs). Trust only its normalized result.
331
+ 2. **Record** it with {@link paymentRecordService}`.store`, which enforces
332
+ `UNIQUE(platformKey, transactionId)` so one receipt binds to exactly ONE account.
333
+ 3. **Resolve** the plan from the verified product/price id against the registered
334
+ {@link plans} (match BOTH `productId` and `priceId`), then grant it.
335
+
336
+ Weak-integration mistakes to avoid:
337
+
338
+ - **Never trust a client-sent plan / subscription / "isPro".** The plan is derived from
339
+ the verified provider result, not a request field.
340
+ - **Never swallow the duplicate-record error.** {@link paymentRecordService}`.store`
341
+ THROWS when a `transactionId` is already claimed — that is the replay guard
342
+ (first-claim-wins). Catch it and REJECT; do not grant the plan to a second account.
343
+ - **Register your catalogue** with {@link registerPlans} using YOUR price/product ids
344
+ (the env-configured `price_…`), and resolve by BOTH product and price id — providers
345
+ report the product on a subscription while checkout uses the price.
346
+ - Re-verify entitlement server-side wherever it gates access; never cache "is subscribed"
347
+ somewhere the client can set.
348
+
349
+ The `payments` table ships in `setup/payments.sql` — an mlcl-scaffolded API
350
+ copies and replays it automatically on migrate; anywhere else run it once.
351
+ Missing it surfaces as `relation "payments" does not exist` on the first
352
+ billing call — nothing at runtime creates the table.
353
+
354
+ ## E2E Tests
355
+
356
+ Integration checklist — drive the real UI (live preview, no mocks), adapt
357
+ each item to this app's actual billing screens/flows, and check every box
358
+ off one by one. A box you can't check is an integration bug to fix — not a
359
+ skip. This resource RECORDS a server-verified provider result (a receipt or
360
+ subscription id verified via `@molecule/api-payments`) and resolves the plan
361
+ — it does NOT charge cards and has no amount/status column, so drive the
362
+ provider's real verify path; never fabricate a record or a status:
363
+
364
+ - [ ] A completed purchase/subscribe flow reflects in the account: the paid
365
+ tier's capabilities unlock and a payment record binds to THIS user with the
366
+ right platformKey (stripe/apple/google), productId/priceId, and
367
+ transactionId — and it appears in the user's own billing/subscription view.
368
+ - [ ] The plan and price shown match what was actually purchased: the tier is
369
+ resolved from the VERIFIED product/price id against the registered plans,
370
+ and any amount/currency shown comes from that plan (its `price`) or the
371
+ provider's verified `data` — never a client-sent field. An amount renders
372
+ formatted with its currency, not as a raw smallest-unit integer.
373
+ - [ ] Status follows the provider, not the client: a verified payment grants
374
+ the plan (pending is granted only once it succeeds), and a provider
375
+ cancellation/refund/expiry webhook (`handlePaymentNotification`) REVOKES it
376
+ so the user loses premium. No request field (`planKey`, `isPro`, a bare
377
+ `subscriptionId`) lets the client set or keep an active/paid status.
378
+ - [ ] Replay and re-complete guard: one receipt/subscription transaction
379
+ binds to exactly ONE account (UNIQUE(platformKey, transactionId),
380
+ first-claim-wins) — replaying the same receipt into a second account is
381
+ REJECTED, re-verifying your own is idempotent (no double grant), and a
382
+ refunded/canceled entitlement can't be reclaimed without a NEW verified
383
+ payment.
384
+ - [ ] Authorization — a user sees only THEIR OWN payments: guessing another
385
+ user's payment/transaction id returns nothing (records scope by userId), and
386
+ NO endpoint lets a user mark their own payment succeeded/refunded or set
387
+ their own plan/isPro to spoof having paid — only the verified provider
388
+ result grants the tier.
389
+ - [ ] The provider secret (e.g. STRIPE_SECRET_KEY / APPLE_SHARED_SECRET /
390
+ GOOGLE_API_SERVICE_KEY_OBJECT) is used only server-side for verification and
391
+ never reaches the browser bundle or a client request — this resource is
392
+ SERVER-ONLY.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource-payment",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Payment resource with subscription plan management",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -18,28 +18,29 @@
18
18
  },
19
19
  "files": [
20
20
  "dist",
21
- "setup"
21
+ "setup",
22
+ "README.md"
22
23
  ],
23
24
  "license": "Apache-2.0",
24
25
  "dependencies": {
25
26
  "zod": "4.4.3"
26
27
  },
27
28
  "devDependencies": {
28
- "@molecule/api-bond": "1.0.0",
29
- "@molecule/api-locales-payment": "1.0.0",
30
- "@molecule/api-payments": "1.0.0",
29
+ "@molecule/api-bond": "1.0.1",
30
+ "@molecule/api-locales-payment": "1.0.1",
31
+ "@molecule/api-payments": "1.0.1",
31
32
  "@types/node": "26.1.2",
32
33
  "typescript": "6.0.3",
33
34
  "vitest": "4.1.10"
34
35
  },
35
36
  "peerDependencies": {
36
- "@molecule/api-bond": "^1.0.0",
37
- "@molecule/api-database": "^1.0.0",
38
- "@molecule/api-i18n": "^1.0.0",
39
- "@molecule/api-locales-payment": "^1.0.0",
40
- "@molecule/api-logger": "^1.0.0",
41
- "@molecule/api-payments": "^1.0.0",
42
- "@molecule/api-resource": "^1.0.0"
37
+ "@molecule/api-bond": "^1.0.1",
38
+ "@molecule/api-database": "^1.0.1",
39
+ "@molecule/api-i18n": "^1.0.1",
40
+ "@molecule/api-locales-payment": "^1.0.1",
41
+ "@molecule/api-logger": "^1.0.1",
42
+ "@molecule/api-payments": "^1.0.1",
43
+ "@molecule/api-resource": "^1.0.1"
43
44
  },
44
45
  "repository": {
45
46
  "type": "git",