@tofound/billing 0.0.0-stage → 0.2.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 +122 -0
- package/LICENSE +3 -0
- package/README.md +79 -2
- package/dist/catalog/catalog.d.ts +115 -0
- package/dist/catalog/catalog.js +201 -0
- package/dist/domain/errors.d.ts +14 -0
- package/dist/domain/errors.js +21 -0
- package/dist/domain/money.d.ts +21 -0
- package/dist/domain/money.js +77 -0
- package/dist/domain/types.d.ts +167 -0
- package/dist/domain/types.js +18 -0
- package/dist/drizzle/index.d.ts +5 -0
- package/dist/drizzle/index.js +5 -0
- package/dist/drizzle/schema-factory.d.ts +586 -0
- package/dist/drizzle/schema-factory.js +206 -0
- package/dist/drizzle/store.d.ts +20 -0
- package/dist/drizzle/store.js +124 -0
- package/dist/entitlement/resolve.d.ts +76 -0
- package/dist/entitlement/resolve.js +122 -0
- package/dist/inbox/apply.d.ts +48 -0
- package/dist/inbox/apply.js +299 -0
- package/dist/inbox/conformance.d.ts +20 -0
- package/dist/inbox/conformance.js +254 -0
- package/dist/inbox/drizzle.d.ts +14 -0
- package/dist/inbox/drizzle.js +203 -0
- package/dist/inbox/ingest.d.ts +108 -0
- package/dist/inbox/ingest.js +404 -0
- package/dist/inbox/memory.d.ts +13 -0
- package/dist/inbox/memory.js +172 -0
- package/dist/inbox/ports.d.ts +150 -0
- package/dist/inbox/ports.js +1 -0
- package/dist/inbox/redact.d.ts +2 -0
- package/dist/inbox/redact.js +47 -0
- package/dist/inbox/schema.d.ts +1158 -0
- package/dist/inbox/schema.js +90 -0
- package/dist/inbox/watermark.d.ts +13 -0
- package/dist/inbox/watermark.js +6 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +27 -0
- package/dist/ledger/ledger.d.ts +47 -0
- package/dist/ledger/ledger.js +224 -0
- package/dist/ports/index.d.ts +2 -0
- package/dist/ports/index.js +1 -0
- package/dist/ports/ledger-store.d.ts +53 -0
- package/dist/ports/ledger-store.js +1 -0
- package/dist/ports/runtime.d.ts +9 -0
- package/dist/ports/runtime.js +1 -0
- package/dist/providers/polar/events.d.ts +17 -0
- package/dist/providers/polar/events.js +213 -0
- package/dist/providers/polar/index.d.ts +50 -0
- package/dist/providers/polar/index.js +271 -0
- package/dist/providers/polar/signature.d.ts +23 -0
- package/dist/providers/polar/signature.js +52 -0
- package/dist/providers/port.d.ts +207 -0
- package/dist/providers/port.js +30 -0
- package/dist/providers/sepay/index.d.ts +34 -0
- package/dist/providers/sepay/index.js +241 -0
- package/dist/providers/sepay/order.d.ts +32 -0
- package/dist/providers/sepay/order.js +69 -0
- package/dist/providers/sepay/signature.d.ts +8 -0
- package/dist/providers/sepay/signature.js +51 -0
- package/dist/quote/conformance.d.ts +16 -0
- package/dist/quote/conformance.js +39 -0
- package/dist/quote/index.d.ts +3 -0
- package/dist/quote/index.js +3 -0
- package/dist/quote/steps.d.ts +54 -0
- package/dist/quote/steps.js +103 -0
- package/dist/quote/waterfall.d.ts +98 -0
- package/dist/quote/waterfall.js +82 -0
- package/dist/renewal/renewal.d.ts +69 -0
- package/dist/renewal/renewal.js +198 -0
- package/dist/stores/conformance.d.ts +22 -0
- package/dist/stores/conformance.js +269 -0
- package/dist/stores/memory.d.ts +19 -0
- package/dist/stores/memory.js +137 -0
- package/dist/stores/testing.d.ts +13 -0
- package/dist/stores/testing.js +13 -0
- package/dist/terms/conformance.d.ts +17 -0
- package/dist/terms/conformance.js +198 -0
- package/dist/terms/decide.d.ts +97 -0
- package/dist/terms/decide.js +176 -0
- package/dist/terms/drizzle.d.ts +12 -0
- package/dist/terms/drizzle.js +131 -0
- package/dist/terms/memory.d.ts +23 -0
- package/dist/terms/memory.js +126 -0
- package/dist/terms/plans.d.ts +85 -0
- package/dist/terms/plans.js +331 -0
- package/dist/terms/ports.d.ts +55 -0
- package/dist/terms/ports.js +1 -0
- package/dist/terms/rules.d.ts +11 -0
- package/dist/terms/rules.js +36 -0
- package/dist/terms/schema.d.ts +711 -0
- package/dist/terms/schema.js +70 -0
- package/dist/terms/snapshot.d.ts +20 -0
- package/dist/terms/snapshot.js +134 -0
- package/dist/terms/types.d.ts +85 -0
- package/dist/terms/types.js +4 -0
- package/docs/API.md +417 -0
- package/docs/SCHEMA.md +163 -0
- package/package.json +80 -4
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider port — the `billing.provider-port` contract (design §5).
|
|
3
|
+
*
|
|
4
|
+
* Every payment provider (SePay, Polar, Apple, Google) is one adapter that
|
|
5
|
+
* turns a raw webhook into verified, normalized events. The inbox
|
|
6
|
+
* (`src/inbox`) persists and applies those events; an adapter never touches
|
|
7
|
+
* storage, reads no env and logs nothing (D14). Changes here are additive
|
|
8
|
+
* within 0.x; every adapter passes the provider conformance suite
|
|
9
|
+
* (`test/fixtures/providers/conformance.ts`).
|
|
10
|
+
*/
|
|
11
|
+
import type { AccountId, Money } from '../domain/types.js';
|
|
12
|
+
export type ProviderId = 'sepay' | 'polar' | 'apple' | 'google';
|
|
13
|
+
/** A provider's rail. Always passed explicitly by the host — never inferred. */
|
|
14
|
+
export type ProviderEnvironment = 'production' | 'sandbox';
|
|
15
|
+
/** The raw HTTP delivery, as the host route received it. */
|
|
16
|
+
export interface InboundRequest {
|
|
17
|
+
headers: Headers;
|
|
18
|
+
/** The exact body bytes as text; signatures are computed over these. */
|
|
19
|
+
rawBody: string;
|
|
20
|
+
url: string;
|
|
21
|
+
receivedAt: Date;
|
|
22
|
+
}
|
|
23
|
+
/** A delivery whose authenticity the adapter has proven. */
|
|
24
|
+
export interface VerifiedDelivery {
|
|
25
|
+
provider: ProviderId;
|
|
26
|
+
environment: ProviderEnvironment;
|
|
27
|
+
/** Provider-unique id of this event; the inbox dedups on `(provider, eventId)`. */
|
|
28
|
+
eventId: string;
|
|
29
|
+
eventType: string;
|
|
30
|
+
occurredAt: Date;
|
|
31
|
+
/** Parsed body. The inbox stores it redacted and normalizes from that copy. */
|
|
32
|
+
payload: unknown;
|
|
33
|
+
/** Server-issued reference the event points at (invoice, external customer id …). */
|
|
34
|
+
subjectRef?: string;
|
|
35
|
+
}
|
|
36
|
+
/** How a provider event names its billing subject — only via server-issued references (§4.1). */
|
|
37
|
+
export interface AccountRef {
|
|
38
|
+
kind: 'account_id' | 'checkout' | 'polar_customer_external_id' | 'apple_app_account_token' | 'google_obfuscated_account';
|
|
39
|
+
value: string;
|
|
40
|
+
}
|
|
41
|
+
export type PurchaseReversalReason = 'refund' | 'chargeback' | 'void' | 'revoke';
|
|
42
|
+
export type SubscriptionSnapshotStatus = 'active' | 'grace' | 'past_due' | 'expired' | 'revoked';
|
|
43
|
+
export interface SubscriptionSnapshotEvent {
|
|
44
|
+
kind: 'subscription.snapshot';
|
|
45
|
+
account: AccountRef;
|
|
46
|
+
externalId: string;
|
|
47
|
+
planRef: string;
|
|
48
|
+
status: SubscriptionSnapshotStatus;
|
|
49
|
+
periodStart: Date;
|
|
50
|
+
periodEnd: Date;
|
|
51
|
+
autoRenew: boolean;
|
|
52
|
+
cancelAtPeriodEnd: boolean;
|
|
53
|
+
graceUntil?: Date;
|
|
54
|
+
nextPlanRef?: string;
|
|
55
|
+
price?: Money;
|
|
56
|
+
occurredAt: Date;
|
|
57
|
+
/**
|
|
58
|
+
* Orders snapshots stamped with the same `occurredAt` (one provider change
|
|
59
|
+
* sent as several events): the greater key wins, the event id settles the
|
|
60
|
+
* rest. Compared as strings; an adapter keeps its keys one width.
|
|
61
|
+
*/
|
|
62
|
+
tieBreak?: string;
|
|
63
|
+
}
|
|
64
|
+
export interface PurchaseCompletedEvent {
|
|
65
|
+
kind: 'purchase.completed';
|
|
66
|
+
account: AccountRef;
|
|
67
|
+
externalId: string;
|
|
68
|
+
productRef: string | null;
|
|
69
|
+
quantity: number;
|
|
70
|
+
amount: Money;
|
|
71
|
+
checkoutRef?: string;
|
|
72
|
+
occurredAt: Date;
|
|
73
|
+
}
|
|
74
|
+
export interface PurchaseChangedEvent {
|
|
75
|
+
kind: 'purchase.reversed' | 'purchase.reinstated';
|
|
76
|
+
externalId: string;
|
|
77
|
+
reason?: PurchaseReversalReason;
|
|
78
|
+
/** The checkout the purchase belongs to, when the provider names it. */
|
|
79
|
+
checkoutRef?: string;
|
|
80
|
+
/** The provider's amount, checked against the purchase when present. */
|
|
81
|
+
amount?: Money;
|
|
82
|
+
occurredAt: Date;
|
|
83
|
+
}
|
|
84
|
+
export type NormalizedEvent = SubscriptionSnapshotEvent | PurchaseCompletedEvent | PurchaseChangedEvent | {
|
|
85
|
+
kind: 'consumption.requested';
|
|
86
|
+
externalId: string;
|
|
87
|
+
occurredAt: Date;
|
|
88
|
+
} | {
|
|
89
|
+
kind: 'checkout.status';
|
|
90
|
+
checkoutRef: string;
|
|
91
|
+
status: string;
|
|
92
|
+
} | {
|
|
93
|
+
kind: 'ignored';
|
|
94
|
+
reason: string;
|
|
95
|
+
}
|
|
96
|
+
/** Authentic but unusable (wrong currency, missing amount …): stored for a human, acknowledged. */
|
|
97
|
+
| {
|
|
98
|
+
kind: 'needs_review';
|
|
99
|
+
reason: string;
|
|
100
|
+
detail?: Record<string, unknown>;
|
|
101
|
+
};
|
|
102
|
+
/** Context an adapter may need while normalizing (re-fetches, clock). */
|
|
103
|
+
export interface NormalizeContext {
|
|
104
|
+
now: Date;
|
|
105
|
+
}
|
|
106
|
+
/** What the inbox did with one delivery; `respond` turns it into the provider's ack. */
|
|
107
|
+
export type IngestStatus = 'applied' | 'ignored' | 'duplicate' | 'needs_review'
|
|
108
|
+
/** Transient: the provider must redeliver. */
|
|
109
|
+
| 'failed'
|
|
110
|
+
/** Gave up after the retry budget; acknowledged so the provider stops. */
|
|
111
|
+
| 'dead'
|
|
112
|
+
/** `verify` refused the credential; nothing was stored. */
|
|
113
|
+
| 'unauthorized'
|
|
114
|
+
/** Authentic transport, unreadable body; nothing was stored. */
|
|
115
|
+
| 'malformed';
|
|
116
|
+
export interface IngestOutcome {
|
|
117
|
+
status: IngestStatus;
|
|
118
|
+
eventId?: string;
|
|
119
|
+
reason?: string;
|
|
120
|
+
/** A host hook's answer to relay verbatim (e.g. Lohi forwarding an unknown SePay invoice). */
|
|
121
|
+
relay?: ProviderResponse;
|
|
122
|
+
}
|
|
123
|
+
/** Framework-agnostic HTTP answer; the host route copies it onto its response. */
|
|
124
|
+
export interface ProviderResponse {
|
|
125
|
+
status: number;
|
|
126
|
+
headers: Record<string, string>;
|
|
127
|
+
body: string;
|
|
128
|
+
}
|
|
129
|
+
export interface ProviderAdapter {
|
|
130
|
+
readonly id: ProviderId;
|
|
131
|
+
readonly environment: ProviderEnvironment;
|
|
132
|
+
/** Prove authenticity. Throws `VerifyError`; on a throw nothing is persisted. */
|
|
133
|
+
verify(req: InboundRequest): Promise<VerifiedDelivery>;
|
|
134
|
+
/**
|
|
135
|
+
* Turn a delivery into domain events. Must be deterministic over the
|
|
136
|
+
* redacted payload, so a manual replay normalizes exactly like the first run.
|
|
137
|
+
*/
|
|
138
|
+
normalize(delivery: VerifiedDelivery, ctx: NormalizeContext): Promise<NormalizedEvent[]>;
|
|
139
|
+
/** The provider's ack convention for an outcome. */
|
|
140
|
+
respond(outcome: IngestOutcome): ProviderResponse;
|
|
141
|
+
/** Drop personal data before the payload is persisted; the inbox has a default. */
|
|
142
|
+
redact?(payload: unknown): unknown;
|
|
143
|
+
}
|
|
144
|
+
export interface CheckoutRequest {
|
|
145
|
+
/** The checkout session id; becomes the provider's invoice / reference. */
|
|
146
|
+
sessionId: string;
|
|
147
|
+
accountId: AccountId;
|
|
148
|
+
amount: Money;
|
|
149
|
+
description: string;
|
|
150
|
+
successUrl: string;
|
|
151
|
+
errorUrl: string;
|
|
152
|
+
cancelUrl: string;
|
|
153
|
+
productRef?: string | null;
|
|
154
|
+
}
|
|
155
|
+
export type CheckoutRedirect = {
|
|
156
|
+
kind: 'redirect';
|
|
157
|
+
url: string;
|
|
158
|
+
}
|
|
159
|
+
/** The client renders a hidden form with `fields` and POSTs it to `url`. */
|
|
160
|
+
| {
|
|
161
|
+
kind: 'form';
|
|
162
|
+
url: string;
|
|
163
|
+
fields: Record<string, string>;
|
|
164
|
+
};
|
|
165
|
+
export interface CheckoutCapable {
|
|
166
|
+
createCheckout(req: CheckoutRequest): Promise<CheckoutRedirect>;
|
|
167
|
+
}
|
|
168
|
+
export interface PortalCapable {
|
|
169
|
+
createPortalSession(account: AccountRef, returnUrl: string): Promise<{
|
|
170
|
+
url: string;
|
|
171
|
+
}>;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Client-proof or poll verification. Yields the same delivery a webhook
|
|
175
|
+
* would, so both take one apply path and credit once; `null` = nothing to
|
|
176
|
+
* apply yet (unpaid, unknown).
|
|
177
|
+
*/
|
|
178
|
+
export interface PurchaseVerifier<TProof = unknown> {
|
|
179
|
+
verifyPurchase(proof: TProof): Promise<VerifiedDelivery | null>;
|
|
180
|
+
}
|
|
181
|
+
export interface Reconcilable {
|
|
182
|
+
listChangesSince(cursor: string | null, limit: number): Promise<{
|
|
183
|
+
deliveries: VerifiedDelivery[];
|
|
184
|
+
next: string | null;
|
|
185
|
+
}>;
|
|
186
|
+
}
|
|
187
|
+
export interface Acknowledger {
|
|
188
|
+
acknowledge(externalId: string): Promise<void>;
|
|
189
|
+
}
|
|
190
|
+
export interface ConsumptionReporter {
|
|
191
|
+
reportConsumption(externalId: string, info: Record<string, unknown>): Promise<void>;
|
|
192
|
+
}
|
|
193
|
+
export declare function isCheckoutCapable<T extends object>(adapter: T): adapter is T & CheckoutCapable;
|
|
194
|
+
export declare function isPurchaseVerifier<T extends object>(adapter: T): adapter is T & PurchaseVerifier;
|
|
195
|
+
/** `verify` refused a delivery: `unauthorized` → 401, `malformed` → 400. Nothing is stored. */
|
|
196
|
+
export declare class VerifyError extends Error {
|
|
197
|
+
readonly name = "VerifyError";
|
|
198
|
+
readonly code: 'unauthorized' | 'malformed';
|
|
199
|
+
constructor(code: 'unauthorized' | 'malformed', message: string);
|
|
200
|
+
}
|
|
201
|
+
/** An adapter was constructed or called with an unusable configuration. */
|
|
202
|
+
export declare class ProviderConfigError extends Error {
|
|
203
|
+
readonly name = "ProviderConfigError";
|
|
204
|
+
readonly code: string;
|
|
205
|
+
constructor(code: string, message: string);
|
|
206
|
+
}
|
|
207
|
+
export declare function isVerifyError(value: unknown): value is VerifyError;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function isCheckoutCapable(adapter) {
|
|
2
|
+
return typeof adapter.createCheckout === 'function';
|
|
3
|
+
}
|
|
4
|
+
export function isPurchaseVerifier(adapter) {
|
|
5
|
+
return typeof adapter.verifyPurchase === 'function';
|
|
6
|
+
}
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
// Errors
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
/** `verify` refused a delivery: `unauthorized` → 401, `malformed` → 400. Nothing is stored. */
|
|
11
|
+
export class VerifyError extends Error {
|
|
12
|
+
name = 'VerifyError';
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** An adapter was constructed or called with an unusable configuration. */
|
|
20
|
+
export class ProviderConfigError extends Error {
|
|
21
|
+
name = 'ProviderConfigError';
|
|
22
|
+
code;
|
|
23
|
+
constructor(code, message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = code;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function isVerifyError(value) {
|
|
29
|
+
return value instanceof VerifyError;
|
|
30
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
|
|
2
|
+
import { type SepayOrderState } from './order.js';
|
|
3
|
+
export { parseSepayOrder, parseVnd, type SepayOrderState } from './order.js';
|
|
4
|
+
export { signCheckoutFields } from './signature.js';
|
|
5
|
+
/** SePay's IPN header carrying the shared webhook key. */
|
|
6
|
+
export declare const SEPAY_SECRET_HEADER = "x-secret-key";
|
|
7
|
+
export interface SepayAdapterOptions {
|
|
8
|
+
/** Required. The host resolves its own policy (e.g. 2Novel's two switches) into this value. */
|
|
9
|
+
environment: ProviderEnvironment;
|
|
10
|
+
/** Accepted `x-secret-key` values; more than one only while rotating. */
|
|
11
|
+
webhookKeys: readonly string[];
|
|
12
|
+
/** Merchant credentials; needed for checkout and order reads, not for IPN verification. */
|
|
13
|
+
merchantId?: string;
|
|
14
|
+
secretKey?: string;
|
|
15
|
+
/** Invoices this host issues; others are ignored as `bad_invoice`. Default: UUID (checkout session ids). */
|
|
16
|
+
invoicePattern?: RegExp;
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
/** Order API timeout. Default 10 s. */
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
/** Poll proof: the checkout session id used as the SePay invoice. */
|
|
22
|
+
export interface SepayPurchaseProof {
|
|
23
|
+
invoice: string;
|
|
24
|
+
}
|
|
25
|
+
export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof> {
|
|
26
|
+
readonly id: 'sepay';
|
|
27
|
+
/** Current order state; `unknown` on any lookup failure. */
|
|
28
|
+
readOrder(invoice: string): Promise<SepayOrderState>;
|
|
29
|
+
/** Cancel, then re-read: a capture that raced the cancellation still reads `paid`. */
|
|
30
|
+
cancelOrder(invoice: string): Promise<SepayOrderState>;
|
|
31
|
+
}
|
|
32
|
+
export declare function createSepayAdapter(options: SepayAdapterOptions): SepayAdapter;
|
|
33
|
+
/** SePay retries any non-2xx; acknowledge everything that a retry cannot change. */
|
|
34
|
+
export declare function respondSepay(outcome: IngestOutcome): ProviderResponse;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SePay payment-gateway adapter (`@tofound/billing/providers/sepay`).
|
|
3
|
+
*
|
|
4
|
+
* One reconciliation of the two host copies (Lohi `api/src/lib/sepay.ts`,
|
|
5
|
+
* 2Novel `2novel/api/src/lib/sepay.ts`), keeping the stricter rule each time:
|
|
6
|
+
* - the environment is required — no default, no inference from key
|
|
7
|
+
* prefixes, and production with test credentials is refused (2Novel's
|
|
8
|
+
* two-switch arming stays a host policy that decides the value passed in);
|
|
9
|
+
* - order reads never turn a lookup failure into a cancellation (Lohi);
|
|
10
|
+
* - `TRANSACTION_VOID` takes precedence over capture fields (Lohi);
|
|
11
|
+
* - a non-VND or unreadable amount is never settled.
|
|
12
|
+
* No SDK and no env reads: checkout fields are signed with `node:crypto`,
|
|
13
|
+
* byte-compatible with `sepay-pg-node@1.0.0`.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { ProviderConfigError, VerifyError, } from '../port.js';
|
|
17
|
+
import { createSepayOrderClient, parseVnd } from './order.js';
|
|
18
|
+
import { signCheckoutFields, webhookKeyMatches } from './signature.js';
|
|
19
|
+
export { parseSepayOrder, parseVnd } from './order.js';
|
|
20
|
+
export { signCheckoutFields } from './signature.js';
|
|
21
|
+
const HOSTS = {
|
|
22
|
+
production: { checkout: 'https://pay.sepay.vn/v1/checkout/init', api: 'https://pgapi.sepay.vn/v1' },
|
|
23
|
+
sandbox: { checkout: 'https://pay-sandbox.sepay.vn/v1/checkout/init', api: 'https://pgapi-sandbox.sepay.vn/v1' },
|
|
24
|
+
};
|
|
25
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26
|
+
/** Field bounds (Lohi validated `order_id` ≤ 64); past them the IPN is refused, not stored. */
|
|
27
|
+
const MAX_EVENT_TYPE = 64;
|
|
28
|
+
const MAX_ORDER_ID = 128;
|
|
29
|
+
/** `test()` on a `g`/`y` RegExp advances `lastIndex`; the copy never does. */
|
|
30
|
+
const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
|
|
31
|
+
/** SePay's IPN header carrying the shared webhook key. */
|
|
32
|
+
export const SEPAY_SECRET_HEADER = 'x-secret-key';
|
|
33
|
+
const TEST_CREDENTIAL = (merchantId, secretKey) => merchantId?.startsWith('SP-TEST-') === true || secretKey?.startsWith('spsk_test_') === true;
|
|
34
|
+
const LIVE_CREDENTIAL = (merchantId, secretKey) => merchantId?.startsWith('SP-LIVE-') === true || secretKey?.startsWith('spsk_live_') === true;
|
|
35
|
+
export function createSepayAdapter(options) {
|
|
36
|
+
const { environment, merchantId, secretKey } = options;
|
|
37
|
+
if (environment !== 'production' && environment !== 'sandbox') {
|
|
38
|
+
throw new ProviderConfigError('sepay_environment_required', 'SePay environment must be passed explicitly: production | sandbox');
|
|
39
|
+
}
|
|
40
|
+
if (environment === 'production' && TEST_CREDENTIAL(merchantId, secretKey)) {
|
|
41
|
+
// A test merchant against the live host is not a charge, it is a 401 in
|
|
42
|
+
// the middle of every checkout; refuse at construction instead.
|
|
43
|
+
throw new ProviderConfigError('sepay_environment_mismatch', 'SePay production environment was given test credentials');
|
|
44
|
+
}
|
|
45
|
+
if (environment === 'sandbox' && LIVE_CREDENTIAL(merchantId, secretKey)) {
|
|
46
|
+
// Live keys against the sandbox host: nobody can pay (2Novel's reverse case).
|
|
47
|
+
throw new ProviderConfigError('sepay_environment_mismatch', 'SePay sandbox environment was given live credentials');
|
|
48
|
+
}
|
|
49
|
+
const webhookKeys = options.webhookKeys.filter((key) => key.length > 0);
|
|
50
|
+
if (webhookKeys.length === 0) {
|
|
51
|
+
throw new ProviderConfigError('sepay_webhook_keys_required', 'at least one SePay webhook key is required');
|
|
52
|
+
}
|
|
53
|
+
const invoicePattern = stateless(options.invoicePattern ?? UUID_RE);
|
|
54
|
+
const hosts = HOSTS[environment];
|
|
55
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
56
|
+
function merchant() {
|
|
57
|
+
if (!merchantId || !secretKey) {
|
|
58
|
+
throw new ProviderConfigError('sepay_not_configured', 'SePay merchant id and secret key are required for checkout and order reads');
|
|
59
|
+
}
|
|
60
|
+
return { merchantId, secretKey };
|
|
61
|
+
}
|
|
62
|
+
let orders = null;
|
|
63
|
+
const orderClient = () => (orders ??= createSepayOrderClient({
|
|
64
|
+
apiBase: hosts.api,
|
|
65
|
+
...merchant(),
|
|
66
|
+
fetch: fetchImpl,
|
|
67
|
+
timeoutMs: options.timeoutMs ?? 10_000,
|
|
68
|
+
}));
|
|
69
|
+
function deliveryOf(body, receivedAt, rawBody) {
|
|
70
|
+
const order = body.order ?? {};
|
|
71
|
+
const type = eventTypeOf(body);
|
|
72
|
+
const orderId = typeof order.order_id === 'string' && order.order_id ? order.order_id : null;
|
|
73
|
+
const invoice = typeof order.order_invoice_number === 'string' && order.order_invoice_number ? order.order_invoice_number : null;
|
|
74
|
+
const ref = orderId ?? (invoice ? `inv:${invoice}` : `sha256:${createHash('sha256').update(rawBody).digest('hex')}`);
|
|
75
|
+
return {
|
|
76
|
+
provider: 'sepay',
|
|
77
|
+
environment,
|
|
78
|
+
eventId: `sepay:${type}:${ref}`,
|
|
79
|
+
eventType: type,
|
|
80
|
+
occurredAt: occurredAtOf(body, receivedAt),
|
|
81
|
+
payload: body,
|
|
82
|
+
...(invoice ? { subjectRef: invoice } : {}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const adapter = {
|
|
86
|
+
id: 'sepay',
|
|
87
|
+
environment,
|
|
88
|
+
async verify(req) {
|
|
89
|
+
if (!webhookKeyMatches(req.headers.get(SEPAY_SECRET_HEADER), webhookKeys)) {
|
|
90
|
+
throw new VerifyError('unauthorized', 'SePay webhook key mismatch');
|
|
91
|
+
}
|
|
92
|
+
let body;
|
|
93
|
+
try {
|
|
94
|
+
body = JSON.parse(req.rawBody);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new VerifyError('malformed', 'SePay IPN body is not JSON');
|
|
98
|
+
}
|
|
99
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
100
|
+
throw new VerifyError('malformed', 'SePay IPN body is not an object');
|
|
101
|
+
}
|
|
102
|
+
const ipn = body;
|
|
103
|
+
const orderId = ipn.order?.order_id;
|
|
104
|
+
if (eventTypeOf(ipn).length > MAX_EVENT_TYPE || (typeof orderId === 'string' && orderId.length > MAX_ORDER_ID)) {
|
|
105
|
+
throw new VerifyError('malformed', 'SePay IPN field out of bounds');
|
|
106
|
+
}
|
|
107
|
+
return deliveryOf(ipn, req.receivedAt, req.rawBody);
|
|
108
|
+
},
|
|
109
|
+
async normalize(delivery) {
|
|
110
|
+
return [normalizeIpn(delivery.payload, delivery.occurredAt, invoicePattern)];
|
|
111
|
+
},
|
|
112
|
+
respond: respondSepay,
|
|
113
|
+
async createCheckout(req) {
|
|
114
|
+
const credentials = merchant();
|
|
115
|
+
if (req.amount.currency !== 'VND' || !Number.isSafeInteger(req.amount.amountMinor) || req.amount.amountMinor <= 0) {
|
|
116
|
+
throw new ProviderConfigError('sepay_invalid_amount', 'SePay charges a positive whole VND amount');
|
|
117
|
+
}
|
|
118
|
+
// The session id is the invoice: one the IPN would ignore must never be charged.
|
|
119
|
+
if (!invoicePattern.test(req.sessionId)) {
|
|
120
|
+
throw new ProviderConfigError('sepay_invalid_invoice', 'checkout session id does not match the adapter invoicePattern');
|
|
121
|
+
}
|
|
122
|
+
// Built in the SDK's field order: the signature covers fields in object order.
|
|
123
|
+
const fields = {
|
|
124
|
+
order_invoice_number: req.sessionId,
|
|
125
|
+
order_amount: String(req.amount.amountMinor),
|
|
126
|
+
order_description: req.description,
|
|
127
|
+
currency: 'VND',
|
|
128
|
+
success_url: req.successUrl,
|
|
129
|
+
error_url: req.errorUrl,
|
|
130
|
+
cancel_url: req.cancelUrl,
|
|
131
|
+
merchant: credentials.merchantId,
|
|
132
|
+
operation: 'PURCHASE',
|
|
133
|
+
};
|
|
134
|
+
return { kind: 'form', url: hosts.checkout, fields: { ...fields, signature: signCheckoutFields(fields, credentials.secretKey) } };
|
|
135
|
+
},
|
|
136
|
+
async verifyPurchase(proof) {
|
|
137
|
+
const order = await orderClient().read(proof.invoice);
|
|
138
|
+
if (order.state !== 'paid')
|
|
139
|
+
return null;
|
|
140
|
+
// Shaped as the IPN would be, so polling and the webhook share one
|
|
141
|
+
// event id and one normalize/apply path.
|
|
142
|
+
const body = {
|
|
143
|
+
notification_type: 'ORDER_PAID',
|
|
144
|
+
order: {
|
|
145
|
+
...(order.orderId ? { order_id: order.orderId } : {}),
|
|
146
|
+
order_invoice_number: proof.invoice,
|
|
147
|
+
order_status: 'CAPTURED',
|
|
148
|
+
order_amount: order.amountVnd,
|
|
149
|
+
order_currency: 'VND',
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
const now = new Date();
|
|
153
|
+
return deliveryOf(body, now, JSON.stringify(body));
|
|
154
|
+
},
|
|
155
|
+
readOrder: async (invoice) => orderClient().read(invoice),
|
|
156
|
+
cancelOrder: async (invoice) => orderClient().cancel(invoice),
|
|
157
|
+
};
|
|
158
|
+
return adapter;
|
|
159
|
+
}
|
|
160
|
+
/** `TRANSACTION_VOID` wins over capture fields; an untyped body counts as paid only when CAPTURED (Lohi). */
|
|
161
|
+
function eventTypeOf(body) {
|
|
162
|
+
const type = typeof body.notification_type === 'string' ? body.notification_type : '';
|
|
163
|
+
if (type)
|
|
164
|
+
return type;
|
|
165
|
+
return body.order?.order_status === 'CAPTURED' ? 'ORDER_PAID' : 'UNKNOWN';
|
|
166
|
+
}
|
|
167
|
+
/** SePay's `timestamp` (unix seconds), else its transaction date (Asia/Ho_Chi_Minh), else receipt time. */
|
|
168
|
+
function occurredAtOf(body, receivedAt) {
|
|
169
|
+
const ts = typeof body.timestamp === 'number' ? body.timestamp : typeof body.timestamp === 'string' ? Number(body.timestamp) : NaN;
|
|
170
|
+
if (Number.isFinite(ts) && ts > 0)
|
|
171
|
+
return new Date(ts * 1000);
|
|
172
|
+
const date = body.transaction?.transaction_date;
|
|
173
|
+
if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date)) {
|
|
174
|
+
const parsed = new Date(`${date.replace(' ', 'T')}+07:00`);
|
|
175
|
+
if (!Number.isNaN(parsed.getTime()))
|
|
176
|
+
return parsed;
|
|
177
|
+
}
|
|
178
|
+
return receivedAt;
|
|
179
|
+
}
|
|
180
|
+
function normalizeIpn(body, occurredAt, invoicePattern) {
|
|
181
|
+
const type = eventTypeOf(body);
|
|
182
|
+
const isVoid = type === 'TRANSACTION_VOID';
|
|
183
|
+
if (!isVoid && type !== 'ORDER_PAID')
|
|
184
|
+
return { kind: 'ignored', reason: `not_settlement:${type}` };
|
|
185
|
+
const order = body.order ?? {};
|
|
186
|
+
const invoice = typeof order.order_invoice_number === 'string' ? order.order_invoice_number : '';
|
|
187
|
+
if (!invoice || !invoicePattern.test(invoice))
|
|
188
|
+
return { kind: 'ignored', reason: 'bad_invoice' };
|
|
189
|
+
// A capture may omit the currency (Lohi); a void must name VND to take money back.
|
|
190
|
+
if ((isVoid || order.order_currency !== undefined) && order.order_currency !== 'VND') {
|
|
191
|
+
return { kind: 'needs_review', reason: 'invalid_currency', detail: { currency: order.order_currency ?? null } };
|
|
192
|
+
}
|
|
193
|
+
const amount = parseVnd(order.order_amount);
|
|
194
|
+
if (amount === null)
|
|
195
|
+
return { kind: 'needs_review', reason: 'invalid_amount', detail: { amount: order.order_amount ?? null } };
|
|
196
|
+
const orderId = typeof order.order_id === 'string' && order.order_id ? order.order_id : null;
|
|
197
|
+
if (isVoid) {
|
|
198
|
+
// A void must name the captured order it reverses (Lohi `dispatchSepayVoid`).
|
|
199
|
+
if (!orderId)
|
|
200
|
+
return { kind: 'needs_review', reason: 'void_without_order_id' };
|
|
201
|
+
return {
|
|
202
|
+
kind: 'purchase.reversed',
|
|
203
|
+
externalId: orderId,
|
|
204
|
+
reason: 'void',
|
|
205
|
+
checkoutRef: invoice,
|
|
206
|
+
amount: { currency: 'VND', amountMinor: amount },
|
|
207
|
+
occurredAt,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
kind: 'purchase.completed',
|
|
212
|
+
account: { kind: 'checkout', value: invoice },
|
|
213
|
+
// No order id → the invoice itself identifies the purchase (one capture per invoice).
|
|
214
|
+
externalId: orderId ?? `inv:${invoice}`,
|
|
215
|
+
productRef: null,
|
|
216
|
+
quantity: 1,
|
|
217
|
+
amount: { currency: 'VND', amountMinor: amount },
|
|
218
|
+
checkoutRef: invoice,
|
|
219
|
+
occurredAt,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
const json = (status, body) => ({
|
|
223
|
+
status,
|
|
224
|
+
headers: { 'content-type': 'application/json' },
|
|
225
|
+
body: JSON.stringify(body),
|
|
226
|
+
});
|
|
227
|
+
/** SePay retries any non-2xx; acknowledge everything that a retry cannot change. */
|
|
228
|
+
export function respondSepay(outcome) {
|
|
229
|
+
if (outcome.relay)
|
|
230
|
+
return outcome.relay;
|
|
231
|
+
switch (outcome.status) {
|
|
232
|
+
case 'unauthorized':
|
|
233
|
+
return json(401, { error: 'Unauthorized' });
|
|
234
|
+
case 'malformed':
|
|
235
|
+
return json(400, { error: 'Invalid JSON' });
|
|
236
|
+
case 'failed':
|
|
237
|
+
return json(500, { error: 'Internal error' });
|
|
238
|
+
default:
|
|
239
|
+
return json(200, { success: true, outcome: outcome.status, ...(outcome.reason ? { reason: outcome.reason } : {}) });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SePay order API (read, cancel), ported from Lohi `api/src/lib/sepay.ts` —
|
|
3
|
+
* the stricter of the two host copies: a lookup failure is never proof of
|
|
4
|
+
* cancellation, and another invoice or currency is never accepted as this
|
|
5
|
+
* purchase.
|
|
6
|
+
*/
|
|
7
|
+
export type SepayOrderState = {
|
|
8
|
+
state: 'unknown';
|
|
9
|
+
} | {
|
|
10
|
+
state: 'pending' | 'cancelled' | 'paid';
|
|
11
|
+
amountVnd: number;
|
|
12
|
+
orderId: string | null;
|
|
13
|
+
};
|
|
14
|
+
/** Parse SePay's order body (`{data: {...}}`) for `invoice`. Anything off is `unknown`. */
|
|
15
|
+
export declare function parseSepayOrder(body: unknown, invoice: string): SepayOrderState;
|
|
16
|
+
/** A positive safe-integer đồng amount from SePay's string-or-number field, else null. */
|
|
17
|
+
export declare function parseVnd(raw: unknown): number | null;
|
|
18
|
+
export interface SepayOrderClientOptions {
|
|
19
|
+
apiBase: string;
|
|
20
|
+
merchantId: string;
|
|
21
|
+
secretKey: string;
|
|
22
|
+
fetch: typeof fetch;
|
|
23
|
+
timeoutMs: number;
|
|
24
|
+
}
|
|
25
|
+
export declare function createSepayOrderClient(options: SepayOrderClientOptions): {
|
|
26
|
+
read: (invoice: string) => Promise<SepayOrderState>;
|
|
27
|
+
/**
|
|
28
|
+
* A 200 cancellation answer is not a state snapshot: re-read the order,
|
|
29
|
+
* so a capture racing the cancellation wins and is still settled.
|
|
30
|
+
*/
|
|
31
|
+
cancel(invoice: string): Promise<SepayOrderState>;
|
|
32
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SePay order API (read, cancel), ported from Lohi `api/src/lib/sepay.ts` —
|
|
3
|
+
* the stricter of the two host copies: a lookup failure is never proof of
|
|
4
|
+
* cancellation, and another invoice or currency is never accepted as this
|
|
5
|
+
* purchase.
|
|
6
|
+
*/
|
|
7
|
+
/** Parse SePay's order body (`{data: {...}}`) for `invoice`. Anything off is `unknown`. */
|
|
8
|
+
export function parseSepayOrder(body, invoice) {
|
|
9
|
+
const data = body?.data;
|
|
10
|
+
if (!data || typeof data !== 'object' || data['order_invoice_number'] !== invoice || data['order_currency'] !== 'VND') {
|
|
11
|
+
return { state: 'unknown' };
|
|
12
|
+
}
|
|
13
|
+
const amountVnd = parseVnd(data['order_amount']);
|
|
14
|
+
if (amountVnd === null)
|
|
15
|
+
return { state: 'unknown' };
|
|
16
|
+
const status = String(data['order_status']);
|
|
17
|
+
const state = status === 'CAPTURED' ? 'paid'
|
|
18
|
+
: status === 'CANCELLED' || status === 'CANCELED' ? 'cancelled'
|
|
19
|
+
: status === 'AUTHENTICATION_NOT_NEEDED' ? 'pending' : null;
|
|
20
|
+
if (!state)
|
|
21
|
+
return { state: 'unknown' };
|
|
22
|
+
// An empty id is absent, as on the IPN path, so both derive one event id.
|
|
23
|
+
return { state, amountVnd, orderId: typeof data['order_id'] === 'string' && data['order_id'] ? data['order_id'] : null };
|
|
24
|
+
}
|
|
25
|
+
/** A positive safe-integer đồng amount from SePay's string-or-number field, else null. */
|
|
26
|
+
export function parseVnd(raw) {
|
|
27
|
+
if ((typeof raw !== 'string' && typeof raw !== 'number') || String(raw).trim() === '')
|
|
28
|
+
return null;
|
|
29
|
+
const value = Number(raw);
|
|
30
|
+
return Number.isSafeInteger(value) && value > 0 ? value : null;
|
|
31
|
+
}
|
|
32
|
+
export function createSepayOrderClient(options) {
|
|
33
|
+
const authorization = `Basic ${Buffer.from(`${options.merchantId}:${options.secretKey}`).toString('base64')}`;
|
|
34
|
+
async function request(path, body) {
|
|
35
|
+
const response = await options.fetch(`${options.apiBase}/${path}`, {
|
|
36
|
+
method: body ? 'POST' : 'GET',
|
|
37
|
+
headers: { Authorization: authorization, 'Content-Type': 'application/json' },
|
|
38
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
39
|
+
signal: AbortSignal.timeout(options.timeoutMs),
|
|
40
|
+
});
|
|
41
|
+
if (!response.ok)
|
|
42
|
+
return null;
|
|
43
|
+
return response.json();
|
|
44
|
+
}
|
|
45
|
+
async function read(invoice) {
|
|
46
|
+
try {
|
|
47
|
+
return parseSepayOrder(await request(`order/detail/${encodeURIComponent(invoice)}`), invoice);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { state: 'unknown' };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
read,
|
|
55
|
+
/**
|
|
56
|
+
* A 200 cancellation answer is not a state snapshot: re-read the order,
|
|
57
|
+
* so a capture racing the cancellation wins and is still settled.
|
|
58
|
+
*/
|
|
59
|
+
async cancel(invoice) {
|
|
60
|
+
try {
|
|
61
|
+
await request('order/cancel', { order_invoice_number: invoice });
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// The re-read below is the answer either way.
|
|
65
|
+
}
|
|
66
|
+
return read(invoice);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** HMAC-SHA256 (base64) over `field=value` pairs joined by `,`, byte-compatible with the SDK. */
|
|
2
|
+
export declare function signCheckoutFields(fields: Record<string, string>, secretKey: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Constant-time match of a presented webhook key against the accepted list
|
|
5
|
+
* (more than one during a rotation). Both sides are hashed first, so the
|
|
6
|
+
* comparison never leaks the expected key's length.
|
|
7
|
+
*/
|
|
8
|
+
export declare function webhookKeyMatches(presented: string | null, accepted: readonly string[]): boolean;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* The fields SePay's hosted checkout signs, as `sepay-pg-node@1.0.0`
|
|
4
|
+
* (`Checkout.signFields`) defines them. Order of signing is the order the
|
|
5
|
+
* fields appear in the submitted object, so the adapter's `createCheckout`
|
|
6
|
+
* builds that object in the SDK's fixed order; fields outside this set are
|
|
7
|
+
* submitted but not signed.
|
|
8
|
+
*/
|
|
9
|
+
const SIGNED_FIELDS = new Set([
|
|
10
|
+
'merchant',
|
|
11
|
+
'env',
|
|
12
|
+
'operation',
|
|
13
|
+
'payment_method',
|
|
14
|
+
'order_amount',
|
|
15
|
+
'currency',
|
|
16
|
+
'order_invoice_number',
|
|
17
|
+
'order_description',
|
|
18
|
+
'customer_id',
|
|
19
|
+
'agreement_id',
|
|
20
|
+
'agreement_name',
|
|
21
|
+
'agreement_type',
|
|
22
|
+
'agreement_payment_frequency',
|
|
23
|
+
'agreement_amount_per_payment',
|
|
24
|
+
'success_url',
|
|
25
|
+
'error_url',
|
|
26
|
+
'cancel_url',
|
|
27
|
+
'order_id',
|
|
28
|
+
]);
|
|
29
|
+
/** HMAC-SHA256 (base64) over `field=value` pairs joined by `,`, byte-compatible with the SDK. */
|
|
30
|
+
export function signCheckoutFields(fields, secretKey) {
|
|
31
|
+
const signed = Object.keys(fields)
|
|
32
|
+
.filter((field) => SIGNED_FIELDS.has(field))
|
|
33
|
+
.map((field) => `${field}=${fields[field] ?? ''}`);
|
|
34
|
+
return createHmac('sha256', secretKey).update(signed.join(',')).digest('base64');
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Constant-time match of a presented webhook key against the accepted list
|
|
38
|
+
* (more than one during a rotation). Both sides are hashed first, so the
|
|
39
|
+
* comparison never leaks the expected key's length.
|
|
40
|
+
*/
|
|
41
|
+
export function webhookKeyMatches(presented, accepted) {
|
|
42
|
+
if (!presented)
|
|
43
|
+
return false;
|
|
44
|
+
const digest = (value) => createHash('sha256').update(value).digest();
|
|
45
|
+
const given = digest(presented);
|
|
46
|
+
let ok = false;
|
|
47
|
+
for (const key of accepted)
|
|
48
|
+
if (key && timingSafeEqual(given, digest(key)))
|
|
49
|
+
ok = true;
|
|
50
|
+
return ok;
|
|
51
|
+
}
|