@theengineerscanvas/payment 0.0.0-stage → 0.1.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ # Security
2
+
3
+ ## Threat Model
4
+
5
+ `@theengineerscanvas/payment` is a payment SDK. It handles API secrets, signs/verifies webhooks, and makes outbound HTTPS calls to payment providers. This document enumerates what the SDK defends against and what it explicitly leaves to the application.
6
+
7
+ ## Secret Management
8
+
9
+ **What the SDK does:**
10
+ - Secrets are read from configuration at `createPaymentClient()` construction time. They are not accepted as method arguments.
11
+ - The `Logger` port auto-redacts keys matching `secret|authorization|password|signature|api[_-]?key|card|pan|cvv` (case-insensitive).
12
+ - Error messages from the SDK never echo raw secrets. The `ProviderError` carries only the provider's own error code, not its full response body.
13
+
14
+ **What the application must do:**
15
+ - Read secrets from `process.env` or a secret manager. Never hardcode them.
16
+ - Rotate keys per your provider's guidance. Rebuild the client when a key changes.
17
+
18
+ ## Webhook Verification
19
+
20
+ ### Raw Body Contract
21
+
22
+ **The `rawBody` passed to `client.webhooks.receive()` MUST be the exact bytes the provider POSTed.** Re-serializing parsed JSON will produce a different byte sequence and cause signature verification to fail.
23
+
24
+ The SDK accepts both `string` and `Uint8Array` for `rawBody` (`Buffer` is a `Uint8Array`, so it works everywhere and remains the recommended path). When bytes are passed, they are HMAC'd directly — no UTF-8 re-encoding occurs:
25
+
26
+ ```ts
27
+ // Next.js (App Router)
28
+ export async function POST(req: Request) {
29
+ const rawBody = Buffer.from(await req.arrayBuffer());
30
+ const signature = req.headers.get("x-paystack-signature") ?? "";
31
+
32
+ const result = await client.webhooks.receive({
33
+ rawBody,
34
+ signature,
35
+ headers: Object.fromEntries(req.headers.entries()),
36
+ });
37
+
38
+ if (!result.ok) {
39
+ return Response.json({ error: result.error.message }, { status: 401 });
40
+ }
41
+
42
+ // Process result.value (WebhookEvent)
43
+ return Response.json({ received: true });
44
+ }
45
+ ```
46
+
47
+ ```ts
48
+ // Hono
49
+ app.post("/webhooks/payment", async (c) => {
50
+ const rawBody = Buffer.from(await c.req.arrayBuffer());
51
+ const sig = c.req.header("x-paystack-signature") ?? "";
52
+
53
+ const result = await client.webhooks.receive({
54
+ rawBody,
55
+ signature: sig,
56
+ headers: c.req.header(),
57
+ });
58
+
59
+ if (!result.ok) {
60
+ return c.json({ error: result.error.message }, 401);
61
+ }
62
+
63
+ return c.json({ received: true });
64
+ });
65
+ ```
66
+
67
+ ```ts
68
+ // Express (requires raw body middleware or custom parser)
69
+ app.post("/webhooks/payment", express.raw({ type: "application/json" }), (req, res) => {
70
+ const result = await client.webhooks.receive({
71
+ rawBody: req.body, // Buffer from express.raw()
72
+ signature: req.headers["x-paystack-signature"] as string,
73
+ headers: req.headers as Record<string, string>,
74
+ });
75
+
76
+ if (!result.ok) {
77
+ return res.status(401).json({ error: result.error.message });
78
+ }
79
+
80
+ res.json({ received: true });
81
+ });
82
+ ```
83
+
84
+ ### Timing-Safe Comparison
85
+
86
+ HMAC comparison uses `crypto.timingSafeEqual`, never `===`. This prevents timing attacks that could leak the correct signature byte-by-byte.
87
+
88
+ ### Replay Defense
89
+
90
+ The parsed `WebhookEvent.id` is exposed as `eventId` on the emitted `webhook.received` event. Applications must persist received `eventId` values and reject duplicates. The SDK does not maintain a deduplication store — this is the application's responsibility.
91
+
92
+ ## Transport Security
93
+
94
+ - All provider HTTP traffic uses HTTPS. `createPaymentClient` rejects an `http://` base URL at construction, and the `HttpClient` additionally reports one as an error at the boundary. A local stub can opt in per provider with `allowInsecureBaseUrl: true`; nothing else can.
95
+ - **Redirects are not followed.** A `3xx` response becomes a non-retryable `ProviderError` naming the status. Following a redirect could reach an `http://` target (breaking the HTTPS-only rule) or a different origin; API endpoints have no legitimate reason to redirect.
96
+ - **`Retry-After` is honoured and bounded.** On `429`/`5xx` the retry delay comes from the provider header (delta-seconds or HTTP-date), capped at 10 seconds so a hostile value cannot stall the caller. Without the header a jittered base delay (500 ms + up to 250 ms) is used to avoid retry storms.
97
+ - **Mutating requests are never retried automatically** — only `GET`/`HEAD`, by default once (`retry.maxRetries`). Retry safety for writes is provider-dependent and documented per provider: Bachs honours an `Idempotency-Key` header, Paystack documents none, so a retried Paystack refund or transfer can repeat. Check `providers.capabilities(id).supportsIdempotencyKey` and reconcile before retrying.
98
+ - Certificate validation is delegated to the runtime (Node 18+/Bun).
99
+
100
+ ## Sensitive Data in Errors
101
+
102
+ - All `PaymentError` subclasses are safe to return to end users. The `message` property contains a generic error string. Detailed diagnostics live in `meta` and `cause`.
103
+ - `InternalError` returns only a `correlationId`. The original error is logged but not exposed in the response.
104
+ - `rawResponse` inside `PaymentAttempt` carries the provider's full response for debugging. Applications must not serialize this to end users. It is flagged as internal in the type JSDoc.
105
+
106
+ ## Dependency Hygiene
107
+
108
+ - v1 has **zero runtime dependencies**. Only Node built-ins: `crypto`, `fetch`, `URL`, `AbortController`, `TextDecoder`.
109
+ - Dev dependencies (`typescript`, `vitest`, `tsup`) are pinned. `npm audit` / `bun audit` is part of the release checklist.
110
+ - Engines: `node >= 18`.
111
+
112
+ ## What the SDK Does NOT Defend Against
113
+
114
+ | Threat | Why out of scope | Mitigation owner |
115
+ |--------|------------------|------------------|
116
+ | Compromised app server | SDK cannot defend a host already lost | App / infra |
117
+ | Provider-side breach | Out of our control | Monitor `webhook.received` vs `payment.succeeded` |
118
+ | SSRF via webhook URL config | App does not configure webhook URLs in v1 | n/a |
119
+ | Replay across processes | SDK is single-process | App persists `WebhookEvent.id` |
120
+ | Phishing of customer | Not a system threat | UX / education |
@@ -0,0 +1,95 @@
1
+ # Versioning
2
+
3
+ `@theengineerscanvas/payment` follows [Semantic Versioning 2.0.0](https://semver.org/).
4
+
5
+ ## Version Format
6
+
7
+ `MAJOR.MINOR.PATCH` (e.g., `1.2.3`)
8
+
9
+ - **MAJOR:** Backward-incompatible API changes
10
+ - **MINOR:** New backward-compatible features
11
+ - **PATCH:** Backward-compatible bug fixes
12
+
13
+ ### Pre-1.0 release candidates
14
+
15
+ Before 1.0.0, releases use the semver prerelease form `0.1.0-rc.N` (for example,
16
+ `0.1.0-rc.16`). The numeric identifier is deliberate: `rc.9` sorts before
17
+ `rc.16`, whereas the historical `RC9`/`RC16` labels compare as text and sort
18
+ backwards.
19
+
20
+ RC16 is published under both the `latest` and `next` dist-tags so a plain
21
+ install works. Later RCs publish under `next` only; `latest` stays on RC16 until
22
+ 1.0.0. A stable release publishes to `latest` and moves `next` with it.
23
+ Consumers must pin the exact version (`--exact` / `--save-exact`) because
24
+ breaking changes are allowed between RCs.
25
+
26
+ ## What Constitutes a Breaking Change
27
+
28
+ - Any change to the public API surface (`src/public-api/index.ts` exports):
29
+ - Removing a type or value export
30
+ - Changing a function signature (parameter type, return type)
31
+ - Changing an interface member's type
32
+ - Changing a branded type's construction (validation becoming stricter)
33
+ - Changing the behavior of a `throw` boundary (e.g., making a previously-thrown error into a `Result`)
34
+ - Dropping support for a Node.js major version
35
+ - Adding a required field to `PaymentClientConfig`
36
+ - Changing `Result<T, E>` shape (the `ok`/`value`/`error` discriminant)
37
+
38
+ ## What Does NOT Constitute a Breaking Change
39
+
40
+ - Adding new optional fields to existing config types
41
+ - Adding new methods to service facades (e.g., new `payments.*` method)
42
+ - Adding new error subclasses (consumers match on `instanceof PaymentError`)
43
+ - Adding new `Provider` literal variants
44
+ - Adding new domain event types (subscriptions are opt-in per event)
45
+ - Changes to the internal API (`application/`, `domain/`, `infrastructure/`)
46
+ - Bug fixes that make validation stricter where the old behavior was clearly wrong
47
+ - Documentation improvements
48
+ - New provider support
49
+
50
+ ## Stability Tiers
51
+
52
+ ### Stable
53
+
54
+ Public API exports that carry backward-compatibility guarantees across minor and patch versions:
55
+
56
+ - `createPaymentClient(config)` factory
57
+ - `PaymentClient` interface
58
+ - `PaymentService`, `RefundService`, `WebhookService` method signatures
59
+ - All error classes (`PaymentError`, `ValidationError`, etc.)
60
+ - `Result<T, E>` type and `ok`/`err` constructors
61
+ - Branded type constructors (`Money`, `PaymentReference`, `Provider`, `Currency`)
62
+
63
+ ### Evolving
64
+
65
+ Service methods may gain new optional parameters in minor versions. Existing required parameters will not change.
66
+
67
+ ### Internal
68
+
69
+ Everything not in `src/public-api/index.ts` is **internal**. No stability guarantees:
70
+
71
+ - Use case functions (`initializePayment`, `refundPayment`, etc.)
72
+ - Adapter implementations (`PaystackAdapter`)
73
+ - Mapper functions (`mapPaystackRefundResponse`)
74
+ - Infrastructure classes (`FetchHttpClient`, `ConsoleLogger`)
75
+ - Domain entities and value objects
76
+ - Provider contract interface (`PaymentProvider`)
77
+
78
+ If your application imports from paths beginning with `../../domain/`, `../../infrastructure/`, or `../../application/`, you are depending on internal API — expect breakage on any version bump.
79
+
80
+ ## Deprecation Policy
81
+
82
+ **v1.x:** No deprecations. All APIs added in v1.0 remain supported through v1.x.
83
+
84
+ **v2.x:** Deprecation will follow Rails-style: deprecated in v2.x, removed in v3.0. Deprecated APIs will emit `console.warn` at runtime and carry `@deprecated` JSDoc annotations.
85
+
86
+ ## v2 Preview
87
+
88
+ Planned for v2 (no timeline):
89
+
90
+ - Provider packages split to `@theengineerscanvas/payment-paystack`, `@theengineerscanvas/payment-stripe`
91
+ - Pluggable retry with backoff strategies
92
+ - Circuit breaker and rate limiter
93
+ - Subscription/recurring payment support
94
+ - Outbox event bus for transactional event persistence
95
+ - Parallel event handler execution
package/llms.txt ADDED
@@ -0,0 +1,97 @@
1
+ # @theengineerscanvas/payment
2
+
3
+ > Framework-agnostic payment SDK for Node 18+. One API over Paystack and Bachs: payments, refunds, transfers/payouts, products, subscriptions, billing customers, and verified webhooks. Zero runtime dependencies, Result-over-throw, money in minor units.
4
+
5
+ ## Agent instructions
6
+
7
+ Read these before writing code against this package:
8
+
9
+ - Money is **minor units** in the SDK (`Money({ amount: 2900, currency: "USD" })` is $29.00). Bachs wants major-unit decimal strings; the adapter converts. Never do currency maths with floats.
10
+ - A `Payment` from a **catalog checkout has no `amount`** until the provider prices it (verify/fetch/webhook). Partial refunds are sized in the charge settlement currency (Bachs), not the charge currency.
11
+ - Expected failures return `Result<T, E>` — check `result.ok`. Only programmer errors throw (`ValidationError`, `ConfigurationError`).
12
+ - Webhooks are the fulfilment source of truth, not redirects. Verify the **raw body** before parsing.
13
+ - Payment references are **app-owned**; the SDK never generates them. `idempotencyKey` is provider-dependent: Bachs documents an `Idempotency-Key` header (and deduplicates refunds by key), Paystack documents none, so a retried Paystack write can repeat — reconcile before retrying (`providers.capabilities(id).supportsIdempotencyKey`).
14
+ - Never log secrets or portal URLs. The logger redacts common secret fields automatically.
15
+ - Capability-specific calls return `UnsupportedProviderError` (code `UNSUPPORTED`); they do not throw.
16
+
17
+ ## Files
18
+
19
+ - [docs/agents/cookbook.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/agents/cookbook.md): task-by-task recipes for every capability — payments, webhooks, refunds, payouts, products, subscriptions, customers, portal, errors, testing.
20
+ - [public-api.json](https://github.com/TheEngineersCanvas/payment/blob/master/public-api.json): machine-readable surface — client facades and methods, provider capabilities, error codes, environment variables, webhook events. Generated and drift-tested.
21
+ - [README.md](https://github.com/TheEngineersCanvas/payment/blob/master/README.md): install, quick start, provider matrix.
22
+ - [docs/bachs-guide.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/bachs-guide.md): Bachs end to end, including subscriptions and payouts.
23
+ - [docs/public-api.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/public-api.md): every type and method signature.
24
+ - [docs/architecture.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/architecture.md): layers, ports, and why the SDK is shaped this way.
25
+ - [docs/migration-guide.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/migration-guide.md): replacing direct provider SDK usage, and the RC15 breaking changes.
26
+ - [docs/integration-checklist.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/integration-checklist.md): production checklist for a Next.js app (Bachs, NGN) — preflight script, Node runtime, webhook/refund rules, go-live order.
27
+ - [docs/bachs-sandbox-validation.md](https://github.com/TheEngineersCanvas/payment/blob/master/docs/bachs-sandbox-validation.md): live Bachs validation — probes, `bun run sandbox:e2e`, webhook endpoint setup, and observed provider behaviour (settlement currency, XOF/XAF precision, webhook payload quirks).
28
+ - [examples/](https://github.com/TheEngineersCanvas/payment/tree/master/examples): Next.js, Express, Hono, and NestJS integration examples.
29
+
30
+ ## Quick start
31
+
32
+ ```ts
33
+ import { createPaymentClient, Money, PaymentReference } from "@theengineerscanvas/payment";
34
+
35
+ const client = createPaymentClient({
36
+ providers: {
37
+ bachs: {
38
+ secretKey: process.env.BACHS_SECRET_KEY!, // sk_sandbox_... or sk_live_...
39
+ webhookSecret: process.env.BACHS_WEBHOOK_SECRET!, // whsec_... (required to verify webhooks)
40
+ },
41
+ },
42
+ defaultProvider: "bachs",
43
+ });
44
+
45
+ const result = await client.payments.initialize({
46
+ amount: Money({ amount: 7500000, currency: "NGN" }), // ₦75,000.00 (omit amount on a catalog checkout: the provider prices the cart)
47
+ reference: PaymentReference("order_123456"),
48
+ customer: { kind: "new", email: "buyer@example.com" },
49
+ callbackUrl: "https://your-app.com/checkout/success",
50
+ idempotencyKey: "checkout_order_123456",
51
+ });
52
+
53
+ if (!result.ok) return { error: result.error.message };
54
+ redirect(result.value.authorizationUrl!); // hosted checkout
55
+ ```
56
+
57
+ Fulfil in the webhook handler, not on the redirect:
58
+
59
+ ```ts
60
+ const event = await client.webhooks.receive({ rawBody, signature, headers });
61
+ if (event.ok && event.value.type === "payment.succeeded") {
62
+ await fulfilOrder(event.value.payload); // payload.charge_id, payload.reference
63
+ }
64
+ ```
65
+
66
+ ## Client surface
67
+
68
+ | Member | Covers |
69
+ |---|---|
70
+ | `payments` | initialize (one-off or catalog checkout), verify, fetch, list |
71
+ | `refunds` | create (full/partial), fetch |
72
+ | `transfers` | bank codes, account resolve, recipients, payout quotes (cross-currency), initiate/fetch/list payouts |
73
+ | `webhooks` | receive + verify, any provider, raw body |
74
+ | `products` | catalog CRUD, archive/unarchive (cursor paged) |
75
+ | `subscriptions` | list, fetch, update (plan/trial/card/metadata), cancel |
76
+ | `customers` | create, fetch, update, list/search, portal sessions |
77
+ | `events` | subscribe to domain events (`payment.succeeded`, `subscription.canceled`, ...) |
78
+ | `providers` | introspect configured providers and their capabilities |
79
+ | `health()` | liveness per provider |
80
+
81
+ ## Providers
82
+
83
+ | Provider | Payments | Refunds | Payouts/transfers | Catalog & subscriptions | Customers & portal |
84
+ |---|---|---|---|---|---|
85
+ | `paystack` | yes | yes | yes | no | no |
86
+ | `bachs` | yes (one-off + catalog) | yes | yes | yes | yes |
87
+
88
+ Capability calls on a provider without support resolve to `UnsupportedProviderError`; no capability
89
+ probing is required.
90
+
91
+ ## Environment variables
92
+
93
+ `createPaymentClient.fromEnv()` reads, in precedence order, `TEC_PAYMENT_*` then provider-native keys:
94
+ `PAYSTACK_SECRET_KEY` / `PAYSTACK_WEBHOOK_SECRET` / `PAYSTACK_BASE_URL`,
95
+ `BACHS_SECRET_KEY` / `BACHS_WEBHOOK_SECRET` / `BACHS_BASE_URL` / `BACHS_TIMEOUT_MS`,
96
+ `TEC_PAYMENT_DEFAULT_PROVIDER`, `TEC_PAYMENT_LOGGING_LEVEL`. `sk_sandbox_` keys route to the
97
+ Bachs sandbox automatically.
package/package.json CHANGED
@@ -1,6 +1,143 @@
1
1
  {
2
2
  "name": "@theengineerscanvas/payment",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-rc.16",
4
+ "description": "Framework-agnostic payment abstraction SDK By TheEngineersCanvas",
5
+ "license": "Apache-2.0",
6
+ "author": "TheEngineersCanvas",
7
+ "keywords": [
8
+ "payment",
9
+ "paystack",
10
+ "bachs",
11
+ "typescript",
12
+ "sdk",
13
+ "nodejs",
14
+ "webhook",
15
+ "refund",
16
+ "subscriptions",
17
+ "billing",
18
+ "llm",
19
+ "ai-agent"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/TheEngineersCanvas/payment.git"
24
+ },
25
+ "homepage": "https://github.com/TheEngineersCanvas/payment#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/TheEngineersCanvas/payment/issues"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "type": "module",
33
+ "main": "./dist/index.cjs",
34
+ "module": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "import": {
39
+ "types": "./dist/index.d.ts",
40
+ "default": "./dist/index.js"
41
+ },
42
+ "require": {
43
+ "types": "./dist/index.d.cts",
44
+ "default": "./dist/index.cjs"
45
+ }
46
+ },
47
+ "./nestjs": {
48
+ "import": {
49
+ "types": "./dist/adapters/nestjs/index.d.ts",
50
+ "default": "./dist/adapters/nestjs/index.js"
51
+ },
52
+ "require": {
53
+ "types": "./dist/adapters/nestjs/index.d.cts",
54
+ "default": "./dist/adapters/nestjs/index.cjs"
55
+ }
56
+ },
57
+ "./package.json": "./package.json"
58
+ },
59
+ "typesVersions": {
60
+ "*": {
61
+ "nestjs": [
62
+ "./dist/adapters/nestjs/index.d.ts"
63
+ ]
64
+ }
65
+ },
66
+ "files": [
67
+ "dist",
68
+ "README.md",
69
+ "LICENSE",
70
+ "llms.txt",
71
+ "public-api.json",
72
+ "docs/agents/cookbook.md",
73
+ "docs/public-api.md",
74
+ "docs/bachs-guide.md",
75
+ "docs/bachs-sandbox-validation.md",
76
+ "docs/integration-checklist.md",
77
+ "docs/security.md",
78
+ "docs/architecture.md",
79
+ "docs/migration-guide.md",
80
+ "docs/versioning.md",
81
+ "docs/api-stability.md",
82
+ "docs/concurrency.md",
83
+ "docs/performance.md",
84
+ "docs/extension-guide.md",
85
+ "docs/provider-guide.md"
86
+ ],
87
+ "engines": {
88
+ "node": ">=18"
89
+ },
90
+ "scripts": {
91
+ "check-types": "tsc --noEmit && tsc --noEmit -p tsconfig.examples.json",
92
+ "test": "vitest run",
93
+ "test:watch": "vitest",
94
+ "test:coverage": "vitest run --coverage",
95
+ "test:dist": "bun run build && vitest run --config tests/smoke/vitest.smoke.config.ts",
96
+ "build": "tsup",
97
+ "lint": "eslint src/ tests/",
98
+ "lint:fix": "eslint --fix src/ tests/",
99
+ "verify": "bash scripts/verify-build.sh",
100
+ "prepublishOnly": "npm run verify",
101
+ "check:docs": "bun run scripts/check-docs-snippets.ts",
102
+ "test:sandbox": "vitest run tests/integration/bachs.spec.ts",
103
+ "sandbox:probe": "bun run scripts/probe-bachs-sandbox.ts",
104
+ "sandbox:money": "bun run scripts/probe-bachs-money.ts",
105
+ "sandbox:xof": "bun run scripts/probe-bachs-xof.ts",
106
+ "sandbox:pay": "bun run scripts/bachs-sandbox-pay.ts",
107
+ "sandbox:e2e": "bun run scripts/bachs-e2e.ts",
108
+ "bachs:preflight": "bun run scripts/bachs-preflight.ts"
109
+ },
110
+ "peerDependencies": {
111
+ "@nestjs/common": "^11",
112
+ "@nestjs/core": "^11",
113
+ "rxjs": "^7"
114
+ },
115
+ "peerDependenciesMeta": {
116
+ "@nestjs/common": {
117
+ "optional": true
118
+ },
119
+ "@nestjs/core": {
120
+ "optional": true
121
+ },
122
+ "rxjs": {
123
+ "optional": true
124
+ }
125
+ },
126
+ "devDependencies": {
127
+ "@nestjs/common": "^11",
128
+ "@nestjs/core": "^11",
129
+ "@nestjs/platform-express": "^11",
130
+ "@nestjs/testing": "^11",
131
+ "@types/node": "^22",
132
+ "@typescript-eslint/eslint-plugin": "^8.64.0",
133
+ "@typescript-eslint/parser": "^8.64.0",
134
+ "@vitest/coverage-v8": "3.2.7",
135
+ "eslint": "^10.7.0",
136
+ "eslint-plugin-boundaries": "^7.0.2",
137
+ "playwright-core": "^1.64.1",
138
+ "rxjs": "^7",
139
+ "tsup": "^8",
140
+ "typescript": "^5",
141
+ "vitest": "^3"
142
+ }
143
+ }