Initial Commit
This commit is contained in:
217
openspec/changes/enterprise-payment/proposal.md
Normal file
217
openspec/changes/enterprise-payment/proposal.md
Normal file
@@ -0,0 +1,217 @@
|
||||
# OpenSpec Change: enterprise-payment
|
||||
|
||||
- **Change ID**: enterprise-payment
|
||||
- **Package**: `@suaveplan/payment`
|
||||
- **Category**: universal
|
||||
- **Target path**: `universal/commerce/payment`
|
||||
- **Status**: IN PROGRESS
|
||||
- **Date**: 2026-04-24
|
||||
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/payment.md`
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Deliver `@suaveplan/payment` on the genesis branch from scratch at enterprise quality. The package provides payment intent lifecycle primitives: a state machine covering `created` → `authorised` → `captured` / `refunded` / `failed` transitions, webhook signature verification with bounded clock-skew (default 300s), idempotency-key enforcement via `@suaveplan/idempotency` (replay returns the recorded outcome, never re-executes), receipt generation (structured data, not HTML), amount arithmetic (integer cents, multi-currency), and a provider-agnostic `PaymentAdapter` interface. Concrete provider adapters live in `@suaveplan/payment-providers`. PCI scope is minimised: the package never stores or transports raw card data; only tokens, intent IDs, and last-four-digit fragments pass through.
|
||||
|
||||
---
|
||||
|
||||
## Current-state audit (genesis)
|
||||
|
||||
The package does not exist on genesis yet — this is a fresh build.
|
||||
|
||||
---
|
||||
|
||||
## Available workspace deps on genesis
|
||||
|
||||
| Package | Role |
|
||||
|---|---|
|
||||
| `@suaveplan/error` (`workspace:^`) | `PaymentError`; `PAYMENT.*` error codes |
|
||||
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock`, `EventBusLike` |
|
||||
| `@suaveplan/events` (`workspace:^`) | Payment lifecycle event bus |
|
||||
| `@suaveplan/idempotency` (`workspace:^`) | Per-transition idempotency key guard |
|
||||
| `@suaveplan/crypto` (`workspace:^`) | Constant-time HMAC for webhook verification |
|
||||
| `@suaveplan/fsm` (`workspace:^`) | FSM interpreter for payment state machine |
|
||||
| `zod` (`catalog:forms`) | Schema validation |
|
||||
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
|
||||
|
||||
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
|
||||
|
||||
---
|
||||
|
||||
## Public API surface
|
||||
|
||||
### Core types
|
||||
|
||||
```ts
|
||||
type PaymentStatus =
|
||||
| 'created' | 'authorised' | 'captured'
|
||||
| 'refunded' | 'partially_refunded' | 'failed' | 'cancelled'
|
||||
|
||||
interface PaymentIntent {
|
||||
id: string
|
||||
status: PaymentStatus
|
||||
amount: number // integer cents
|
||||
currency: string // ISO 4217 e.g. 'GBP'
|
||||
description?: string
|
||||
token?: string // provider payment method token; no raw card data
|
||||
lastFour?: string
|
||||
metadata: Record<string, unknown>
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
history: PaymentTransition[]
|
||||
}
|
||||
|
||||
interface PaymentTransition {
|
||||
from: PaymentStatus
|
||||
to: PaymentStatus
|
||||
idempotencyKey: string
|
||||
timestamp: Date
|
||||
actor?: string
|
||||
}
|
||||
|
||||
interface Receipt {
|
||||
intentId: string
|
||||
amount: number
|
||||
currency: string
|
||||
formattedAmount: string // e.g. '£12.50'
|
||||
status: PaymentStatus
|
||||
transitions: PaymentTransition[]
|
||||
issuedAt: Date
|
||||
}
|
||||
```
|
||||
|
||||
### `PaymentAdapter` interface
|
||||
|
||||
```ts
|
||||
interface PaymentAdapter {
|
||||
readonly provider: string
|
||||
create(options: CreatePaymentOptions): Promise<PaymentIntent>
|
||||
authorise(intentId: string, token: string, idempotencyKey: string): Promise<PaymentIntent>
|
||||
capture(intentId: string, amount: number, idempotencyKey: string): Promise<PaymentIntent>
|
||||
refund(intentId: string, amount: number, idempotencyKey: string): Promise<PaymentIntent>
|
||||
cancel(intentId: string, idempotencyKey: string): Promise<PaymentIntent>
|
||||
verifyWebhook(body: string, headers: Record<string, string>, secret: string): boolean
|
||||
normalizeWebhook(body: unknown): PaymentWebhookEvent[]
|
||||
}
|
||||
```
|
||||
|
||||
### `PaymentService`
|
||||
|
||||
```ts
|
||||
class PaymentService {
|
||||
constructor(options: PaymentServiceOptions)
|
||||
create(options: CreatePaymentOptions): Promise<PaymentIntent>
|
||||
authorise(intentId: string, token: string): Promise<PaymentIntent>
|
||||
capture(intentId: string, amount?: number): Promise<PaymentIntent>
|
||||
refund(intentId: string, amount?: number): Promise<PaymentIntent>
|
||||
cancel(intentId: string): Promise<PaymentIntent>
|
||||
getReceipt(intentId: string): Receipt
|
||||
}
|
||||
|
||||
interface PaymentServiceOptions {
|
||||
adapter: PaymentAdapter
|
||||
store?: PaymentStore
|
||||
idempotency?: IdempotencyGuard
|
||||
logger?: LoggerLike
|
||||
clock?: Clock
|
||||
bus?: EventBusLike
|
||||
}
|
||||
```
|
||||
|
||||
### Amount utilities
|
||||
|
||||
```ts
|
||||
function formatAmount(amount: number, currency: string, locale?: string): string
|
||||
function toMinorUnits(major: number, currency: string): number
|
||||
function fromMinorUnits(minor: number, currency: string): number
|
||||
function addAmounts(a: number, b: number): number
|
||||
function subtractAmounts(a: number, b: number): number // throws if negative
|
||||
```
|
||||
|
||||
### Error codes
|
||||
|
||||
```ts
|
||||
type PaymentErrorCode =
|
||||
| 'PAYMENT_NOT_FOUND'
|
||||
| 'PAYMENT_INVALID_TRANSITION'
|
||||
| 'PAYMENT_SIGNATURE_FAILED'
|
||||
| 'PAYMENT_REPLAY_DETECTED'
|
||||
| 'PAYMENT_IDEMPOTENCY_CONFLICT'
|
||||
| 'PAYMENT_AMOUNT_INVALID'
|
||||
| 'PAYMENT_PROVIDER_ERROR'
|
||||
| 'PAYMENT_ABORTED'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Genesis additions
|
||||
|
||||
1. **`PaymentError`** extends `SuaveplanError` with eight stable codes.
|
||||
2. **Zod schemas** for `PaymentIntent`, `PaymentTransition`, `Receipt`, `CreatePaymentOptions`, `PaymentWebhookEvent`.
|
||||
3. **State machine** — implemented via `@suaveplan/fsm`; illegal transitions surface `PAYMENT_INVALID_TRANSITION` with full history in the error context.
|
||||
4. **Idempotency enforcement** — every state-altering method requires an idempotency key passed through `@suaveplan/idempotency`; replay returns the cached `PaymentIntent` without re-executing the provider call.
|
||||
5. **Webhook verification** — constant-time HMAC via `@suaveplan/crypto`; bounded clock-skew rejects webhooks older than 300s (configurable); nonce dedup window prevents replay.
|
||||
6. **PCI minimisation** — `token` and `lastFour` fields only; no `pan`, `cvv`, `expiry` in any type.
|
||||
7. **OTel instrumentation** — span `payment.transition` with attributes `payment.from_status`, `payment.to_status`, `payment.provider`; counter `payment.transition_total`; histogram `payment.transition_duration_ms`.
|
||||
8. **Property-based tests** — state machine reachability: every valid transition chain from `created` eventually reaches a terminal state; amount arithmetic properties (commutativity of add, non-negativity of subtract).
|
||||
|
||||
---
|
||||
|
||||
## File layout
|
||||
|
||||
```text
|
||||
universal/commerce/payment/
|
||||
package.json
|
||||
tsconfig.json
|
||||
vitest.config.ts
|
||||
src/
|
||||
index.ts
|
||||
error-codes.ts
|
||||
constants/
|
||||
index.ts # ALLOWED_TRANSITIONS, TERMINAL_STATUSES, DEFAULT_SKEW_MS
|
||||
types/
|
||||
common.ts
|
||||
common.md
|
||||
core/
|
||||
payment-service/
|
||||
payment-service.ts
|
||||
payment-service.md
|
||||
payment-service.types.ts
|
||||
payment-service.test.ts
|
||||
index.ts
|
||||
payment-fsm/
|
||||
payment-fsm.ts
|
||||
payment-fsm.md
|
||||
payment-fsm.test.ts
|
||||
index.ts
|
||||
webhook/
|
||||
webhook-verifier/
|
||||
webhook-verifier.ts
|
||||
webhook-verifier.md
|
||||
webhook-verifier.test.ts
|
||||
index.ts
|
||||
receipt/
|
||||
receipt-generator/
|
||||
receipt-generator.ts
|
||||
receipt-generator.md
|
||||
receipt-generator.test.ts
|
||||
index.ts
|
||||
utils/
|
||||
amount.ts
|
||||
amount.md
|
||||
amount.test.ts
|
||||
__benchmarks__/
|
||||
payment.bench.ts
|
||||
tests/
|
||||
integration.test.ts
|
||||
property.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Impact
|
||||
|
||||
**Downstream consumers**: `@suaveplan/payment-providers`, `@suaveplan/booking`.
|
||||
|
||||
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/idempotency`, `@suaveplan/crypto`, `@suaveplan/fsm`.
|
||||
72
openspec/changes/enterprise-payment/tasks.md
Normal file
72
openspec/changes/enterprise-payment/tasks.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# Tasks: enterprise-payment
|
||||
|
||||
**Change ID**: enterprise-payment
|
||||
**Package**: `@suaveplan/payment`
|
||||
**Target path**: `universal/commerce/payment`
|
||||
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/idempotency`, `@suaveplan/crypto`, `@suaveplan/fsm`
|
||||
|
||||
---
|
||||
|
||||
## 0. Pre-flight (non-negotiable)
|
||||
|
||||
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
|
||||
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
|
||||
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
|
||||
|
||||
## 1. Scaffold
|
||||
|
||||
- [ ] Create `universal/commerce/payment/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
|
||||
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
|
||||
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
|
||||
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
|
||||
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
|
||||
|
||||
---
|
||||
|
||||
## 2. Types + errors
|
||||
|
||||
- [ ] `src/types/common.ts` — `PaymentStatus`, `PaymentIntent`, `PaymentTransition`, `Receipt`, `CreatePaymentOptions`, `PaymentWebhookEvent`, `PaymentAdapter` (interface), `PaymentStore` (interface), `PaymentServiceOptions`.
|
||||
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
|
||||
- [ ] `src/error-codes.ts` — `PaymentErrorCode` (8 codes), metadata, register, eager call.
|
||||
- [ ] `src/constants/index.ts` — `ALLOWED_TRANSITIONS` map, `TERMINAL_STATUSES` set, `DEFAULT_CLOCK_SKEW_MS = 300_000`.
|
||||
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas. Note: `PaymentIntent` schema must NOT include `pan`, `cvv`, or `expiry` fields.
|
||||
|
||||
---
|
||||
|
||||
## 3. Core modules
|
||||
|
||||
- [ ] **`src/core/payment-fsm/`** — `PaymentFsm`: wraps `@suaveplan/fsm`; defines all valid transitions per `ALLOWED_TRANSITIONS`; `transition(intent, to, key)` checks legality, throws `PAYMENT_INVALID_TRANSITION` if illegal, returns new `PaymentIntent` with updated status and appended `PaymentTransition`. Tests: all legal transitions, two illegal transitions, transition adds history entry.
|
||||
- [ ] **`src/webhook/webhook-verifier/`** — `WebhookVerifier.verify(body, secret, timestamp, signature)`: constant-time HMAC via `@suaveplan/crypto`; checks `|now - timestamp| <= skewMs`; throws `PAYMENT_SIGNATURE_FAILED` on mismatch, `PAYMENT_SIGNATURE_FAILED` on expired. Tests: valid, tampered, expired, missing timestamp.
|
||||
- [ ] **`src/receipt/receipt-generator/`** — `generateReceipt(intent): Receipt`: maps intent fields; `formattedAmount` uses `Intl.NumberFormat` with currency. Tests: GBP formatting, USD formatting, partial refund status, all terminal statuses.
|
||||
- [ ] **`src/utils/amount.ts`** — `formatAmount`, `toMinorUnits`, `fromMinorUnits`, `addAmounts`, `subtractAmounts`. `subtractAmounts` throws `PAYMENT_AMOUNT_INVALID` if result < 0. Tests: all functions, negative subtraction throws.
|
||||
- [ ] **`src/core/payment-service/`** — `PaymentService`: `create`, `authorise`, `capture`, `refund`, `cancel` — each wraps state transition with idempotency guard (from `options.idempotency`); calls `options.adapter` for provider interaction; stores result in `options.store`; emits event on `options.bus`. `getReceipt(intentId)` fetches from store and calls `generateReceipt`. Tests: happy path create→authorise→capture, duplicate idempotency key returns cached result, refund > captured amount throws, `cancel` from terminal state throws.
|
||||
|
||||
---
|
||||
|
||||
## 4. OTel instrumentation
|
||||
|
||||
- [ ] Span `payment.transition` with attributes `payment.from_status`, `payment.to_status`, `payment.provider`; counter `payment.transition_total`; histogram `payment.transition_duration_ms`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Property-based tests (`tests/property.test.ts`)
|
||||
|
||||
- [ ] State machine reachability: every valid create→terminal path through `ALLOWED_TRANSITIONS` terminates in `captured`, `refunded`, `failed`, or `cancelled`.
|
||||
- [ ] Amount arithmetic: `addAmounts(a, b) === addAmounts(b, a)` for non-negative integers; `fromMinorUnits(toMinorUnits(x, 'GBP'), 'GBP') === x` for 0–1 000 000.
|
||||
|
||||
---
|
||||
|
||||
## 6. Benchmarks (`src/__benchmarks__/payment.bench.ts`)
|
||||
|
||||
- [ ] `PaymentFsm.transition` 100 000 times.
|
||||
- [ ] `generateReceipt` 100 000 times.
|
||||
|
||||
---
|
||||
|
||||
## 7. Docs + verify
|
||||
|
||||
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
|
||||
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/payment` — green.
|
||||
- [ ] `bunx turbo test:coverage --filter=@suaveplan/payment` — 100%.
|
||||
- [ ] `bun scripts/publish.ts --package @suaveplan/payment`.
|
||||
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-payment/`.
|
||||
Reference in New Issue
Block a user