@miniduckco/stash 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Miniduck Co
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # @miniduck/stash
2
+
3
+ Integrate payments in under 15 minutes.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @miniduck/stash
9
+ ```
10
+
11
+ ## Getting started
12
+
13
+ Start with the quickstart tutorial: `docs/tutorials/quickstart.md`.
14
+
15
+ ## Docs (Diataxis)
16
+
17
+ - Tutorials: `docs/tutorials/quickstart.md`
18
+ - How-to guides: `docs/how-to/README.md`
19
+ - Reference: `docs/reference/api.md`
20
+ - Explanation: `docs/explanation/architecture.md`
21
+ - Skills quick reference: `doc/skill.md`
22
+
23
+ ## Examples
24
+
25
+ Runnable examples live in `examples/`:
26
+
27
+ - Index: `examples/README.md`
28
+
29
+ ## Site (SvelteKit)
30
+
31
+ The landing page + docs site lives in `site/` and renders markdown directly from `docs/`.
32
+
33
+ Local dev:
34
+
35
+ ```bash
36
+ npm install --prefix site
37
+ npm run dev --prefix site -- --host 0.0.0.0 --port 5173
38
+ ```
39
+
40
+ Docker preview:
41
+
42
+ ```bash
43
+ docker build -t stash-site .
44
+ docker run --rm -p 5173:5173 stash-site
45
+ ```
46
+
47
+ ## Providers and operations
48
+
49
+ Providers
50
+ - [x] Ozow
51
+ - [x] Payfast
52
+ - [x] Paystack
53
+ - [ ] Paygate
54
+ - [ ] Peach
55
+
56
+ Supported operations
57
+ - [x] payments.create
58
+ - [x] payments.verify (Ozow, Paystack; Payfast unsupported)
59
+ - [x] webhooks.parse
60
+
61
+ Notes:
62
+ - Ozow hash excludes `CustomerCellphoneNumber`, `Token`, and `GenerateShortUrl`.
63
+ - Ozow `AllowVariableAmount=false` is excluded from the hash.
64
+ - Payfast signature excludes `setup` and requires uppercase URL encoding.
@@ -0,0 +1,4 @@
1
+ export declare class StashError extends Error {
2
+ readonly code: string;
3
+ constructor(code: string, message: string);
4
+ }
@@ -0,0 +1,7 @@
1
+ export class StashError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.code = code;
5
+ this.name = "StashError";
6
+ }
7
+ }
@@ -0,0 +1,21 @@
1
+ import type { ParsedWebhook, Payment, PaymentCreateInput, PaymentVerifyInput, PaymentRequest, PaymentResponse, StashConfig, VerificationResult, WebhookParseInput, WebhookVerifyInput, WebhookVerifyResult } from "./types.js";
2
+ export type { OzowProviderOptions, ParsedWebhook, Payment, PaymentCreateInput, PaymentProvider, PaymentVerifyInput, PaymentRequest, PaymentResponse, PaystackProviderOptions, PayfastProviderOptions, ProviderOptions, StashConfig, VerificationResult, WebhookEvent, WebhookParseInput, WebhookVerifyInput, WebhookVerifyResult, } from "./types.js";
3
+ export { StashError } from "./errors.js";
4
+ export { buildFormEncoded, parseFormBody, parseFormEncoded, pairsToRecord } from "./internal/form.js";
5
+ export declare function createStash(config: StashConfig): {
6
+ payments: {
7
+ create: (input: PaymentCreateInput) => Promise<Payment>;
8
+ verify: (input: PaymentVerifyInput) => Promise<VerificationResult>;
9
+ };
10
+ webhooks: {
11
+ parse: (input: WebhookParseInput) => ParsedWebhook;
12
+ };
13
+ };
14
+ /**
15
+ * @deprecated Use createStash({ provider, credentials }).payments.create instead.
16
+ */
17
+ export declare function makePayment(input: PaymentRequest): Promise<PaymentResponse>;
18
+ /**
19
+ * @deprecated Use createStash({ provider, credentials }).webhooks.parse instead.
20
+ */
21
+ export declare function verifyWebhookSignature(input: WebhookVerifyInput): WebhookVerifyResult;
@@ -0,0 +1,160 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { formatAmount } from "./internal/guards.js";
3
+ import { StashError } from "./errors.js";
4
+ import { providerAdapters } from "./providers/adapters.js";
5
+ import { makeOzowPayment, verifyOzowWebhook } from "./providers/ozow.js";
6
+ import { makePayfastPayment, verifyPayfastWebhook } from "./providers/payfast.js";
7
+ import { makePaystackPayment, verifyPaystackWebhook } from "./providers/paystack.js";
8
+ export { StashError } from "./errors.js";
9
+ export { buildFormEncoded, parseFormBody, parseFormEncoded, pairsToRecord } from "./internal/form.js";
10
+ export function createStash(config) {
11
+ const provider = config.provider;
12
+ const testMode = config.testMode ?? false;
13
+ return {
14
+ payments: {
15
+ create: async (input) => {
16
+ const currency = input.currency ?? config.defaults?.currency ?? "ZAR";
17
+ const amountNumber = Number(formatAmount(input.amount));
18
+ const paymentRequest = {
19
+ provider,
20
+ amount: input.amount,
21
+ currency,
22
+ reference: input.reference,
23
+ description: input.description,
24
+ customer: input.customer,
25
+ urls: input.urls,
26
+ metadata: input.metadata,
27
+ providerOptions: input.providerOptions,
28
+ providerData: input.providerData,
29
+ testMode,
30
+ secrets: buildSecrets(provider, config.credentials),
31
+ };
32
+ const adapter = providerAdapters[provider];
33
+ const response = await adapter.createPayment(paymentRequest);
34
+ return {
35
+ id: randomUUID(),
36
+ status: "pending",
37
+ amount: amountNumber,
38
+ currency,
39
+ redirectUrl: response.redirectUrl,
40
+ provider,
41
+ providerRef: response.paymentRequestId,
42
+ raw: response.raw ?? response,
43
+ };
44
+ },
45
+ verify: async (input) => {
46
+ const adapter = providerAdapters[provider];
47
+ if (!adapter?.verifyPayment) {
48
+ throw new StashError("unsupported_capability", `payments.verify is not supported for ${provider}`);
49
+ }
50
+ return adapter.verifyPayment({
51
+ reference: input.reference,
52
+ secrets: buildSecrets(provider, config.credentials),
53
+ testMode,
54
+ });
55
+ },
56
+ },
57
+ webhooks: {
58
+ parse: (input) => {
59
+ const resolvedProvider = input.provider ?? provider;
60
+ const secrets = buildSecrets(resolvedProvider, config.credentials);
61
+ const rawBody = input.rawBody;
62
+ const adapter = providerAdapters[resolvedProvider];
63
+ if (!adapter) {
64
+ throw new Error(`Unsupported provider: ${resolvedProvider}`);
65
+ }
66
+ const parsed = adapter.parseWebhook({
67
+ rawBody,
68
+ headers: input.headers,
69
+ secrets,
70
+ });
71
+ if (!parsed.isValid) {
72
+ throw new StashError("invalid_signature", `Invalid ${resolvedProvider} signature`);
73
+ }
74
+ return {
75
+ event: parsed.event,
76
+ provider: resolvedProvider,
77
+ raw: parsed.raw,
78
+ };
79
+ },
80
+ },
81
+ };
82
+ }
83
+ function buildSecrets(provider, credentials) {
84
+ if (provider === "ozow") {
85
+ const ozow = credentials;
86
+ return {
87
+ siteCode: ozow.siteCode,
88
+ apiKey: ozow.apiKey,
89
+ privateKey: ozow.privateKey,
90
+ };
91
+ }
92
+ const payfast = credentials;
93
+ if (provider === "payfast") {
94
+ return {
95
+ merchantId: payfast.merchantId,
96
+ merchantKey: payfast.merchantKey,
97
+ passphrase: payfast.passphrase,
98
+ };
99
+ }
100
+ const paystack = credentials;
101
+ return {
102
+ paystackSecretKey: paystack.secretKey,
103
+ };
104
+ }
105
+ /**
106
+ * @deprecated Use createStash({ provider, credentials }).payments.create instead.
107
+ */
108
+ export async function makePayment(input) {
109
+ switch (input.provider) {
110
+ case "ozow":
111
+ return makeOzowPayment(input);
112
+ case "payfast":
113
+ return makePayfastPayment(input);
114
+ case "paystack":
115
+ return makePaystackPayment(input);
116
+ default:
117
+ throw new Error(`Unsupported provider: ${input.provider}`);
118
+ }
119
+ }
120
+ /**
121
+ * @deprecated Use createStash({ provider, credentials }).webhooks.parse instead.
122
+ */
123
+ export function verifyWebhookSignature(input) {
124
+ switch (input.provider) {
125
+ case "ozow":
126
+ return verifyOzowWebhook(input);
127
+ case "payfast":
128
+ return verifyPayfastWebhook(input);
129
+ case "paystack": {
130
+ const signature = resolveHeader(input.headers, "x-paystack-signature");
131
+ const secretKey = input.secrets.paystackSecretKey;
132
+ if (!input.rawBody || !secretKey) {
133
+ return {
134
+ provider: "paystack",
135
+ isValid: false,
136
+ reason: "missingPayload",
137
+ };
138
+ }
139
+ return {
140
+ provider: "paystack",
141
+ isValid: verifyPaystackWebhook(input.rawBody, signature, secretKey),
142
+ };
143
+ }
144
+ default:
145
+ throw new Error(`Unsupported provider: ${input.provider}`);
146
+ }
147
+ }
148
+ function resolveHeader(headers, key) {
149
+ if (!headers)
150
+ return undefined;
151
+ const lowerKey = key.toLowerCase();
152
+ for (const [headerKey, value] of Object.entries(headers)) {
153
+ if (headerKey.toLowerCase() !== lowerKey)
154
+ continue;
155
+ if (Array.isArray(value))
156
+ return value[0];
157
+ return value;
158
+ }
159
+ return undefined;
160
+ }
@@ -0,0 +1,2 @@
1
+ export declare function encodePayfastValue(value: string): string;
2
+ export declare function decodeFormComponent(value: string): string;
@@ -0,0 +1,10 @@
1
+ export function encodePayfastValue(value) {
2
+ const encoded = encodeURIComponent(value)
3
+ .replace(/%[0-9a-f]{2}/gi, (match) => match.toUpperCase())
4
+ .replace(/%20/g, "+");
5
+ return encoded;
6
+ }
7
+ export function decodeFormComponent(value) {
8
+ const replaced = value.replace(/\+/g, " ");
9
+ return decodeURIComponent(replaced);
10
+ }
@@ -0,0 +1,5 @@
1
+ export type FormPair = [string, string];
2
+ export declare function parseFormEncoded(raw: string): FormPair[];
3
+ export declare function pairsToRecord(pairs: FormPair[]): Record<string, string>;
4
+ export declare function parseFormBody(rawBody: string | Buffer): FormPair[];
5
+ export declare function buildFormEncoded(payload: Record<string, string | number | boolean | null | undefined>): string;
@@ -0,0 +1,40 @@
1
+ import { decodeFormComponent } from "./encoding.js";
2
+ function encodeFormComponent(value) {
3
+ return encodeURIComponent(value).replace(/%20/g, "+");
4
+ }
5
+ export function parseFormEncoded(raw) {
6
+ if (!raw) {
7
+ return [];
8
+ }
9
+ return raw
10
+ .split("&")
11
+ .filter((pair) => pair.length > 0)
12
+ .map((pair) => {
13
+ const index = pair.indexOf("=");
14
+ if (index === -1) {
15
+ return [decodeFormComponent(pair), ""];
16
+ }
17
+ const key = pair.slice(0, index);
18
+ const value = pair.slice(index + 1);
19
+ return [decodeFormComponent(key), decodeFormComponent(value)];
20
+ });
21
+ }
22
+ export function pairsToRecord(pairs) {
23
+ return pairs.reduce((acc, [key, value]) => {
24
+ acc[key] = value;
25
+ return acc;
26
+ }, {});
27
+ }
28
+ export function parseFormBody(rawBody) {
29
+ const text = Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : rawBody;
30
+ return parseFormEncoded(text);
31
+ }
32
+ export function buildFormEncoded(payload) {
33
+ const pairs = [];
34
+ for (const [key, value] of Object.entries(payload)) {
35
+ if (value === undefined || value === null)
36
+ continue;
37
+ pairs.push(`${encodeFormComponent(key)}=${encodeFormComponent(String(value))}`);
38
+ }
39
+ return pairs.join("&");
40
+ }
@@ -0,0 +1,3 @@
1
+ export declare function requireValue<T>(value: T | undefined | null, name: string): T;
2
+ export declare function formatAmount(value: string | number): string;
3
+ export declare function toStringValue(value: string | number | boolean): string;
@@ -0,0 +1,19 @@
1
+ export function requireValue(value, name) {
2
+ if (value === undefined || value === null || value === "") {
3
+ throw new Error(`Missing required value: ${name}`);
4
+ }
5
+ return value;
6
+ }
7
+ export function formatAmount(value) {
8
+ const numeric = typeof value === "number" ? value : Number(value);
9
+ if (!Number.isFinite(numeric)) {
10
+ throw new Error("Amount must be a valid number");
11
+ }
12
+ return numeric.toFixed(2);
13
+ }
14
+ export function toStringValue(value) {
15
+ if (typeof value === "boolean") {
16
+ return value ? "true" : "false";
17
+ }
18
+ return String(value);
19
+ }
@@ -0,0 +1,2 @@
1
+ export declare function sha512Hex(input: string): string;
2
+ export declare function md5Hex(input: string): string;
@@ -0,0 +1,7 @@
1
+ import { createHash } from "node:crypto";
2
+ export function sha512Hex(input) {
3
+ return createHash("sha512").update(input).digest("hex");
4
+ }
5
+ export function md5Hex(input) {
6
+ return createHash("md5").update(input).digest("hex");
7
+ }
@@ -0,0 +1,6 @@
1
+ import type { PaymentRequest } from "../types.js";
2
+ import type { ProviderAdapter } from "./provider-adapter.js";
3
+ export declare const ozowAdapter: ProviderAdapter;
4
+ export declare const payfastAdapter: ProviderAdapter;
5
+ export declare const paystackAdapter: ProviderAdapter;
6
+ export declare const providerAdapters: Record<PaymentRequest["provider"], ProviderAdapter>;
@@ -0,0 +1,198 @@
1
+ import { pairsToRecord, parseFormEncoded } from "../internal/form.js";
2
+ import { makeOzowPayment, verifyOzowWebhook } from "./ozow.js";
3
+ import { makePayfastPayment, verifyPayfastWebhook } from "./payfast.js";
4
+ import { makePaystackPayment, verifyPaystackPayment, verifyPaystackWebhook } from "./paystack.js";
5
+ function parseWebhookPayload(rawBody) {
6
+ const raw = Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : rawBody;
7
+ return pairsToRecord(parseFormEncoded(raw));
8
+ }
9
+ function mapPayfastEvent(payload) {
10
+ const status = (payload.payment_status ?? "").toUpperCase();
11
+ const type = status === "COMPLETE"
12
+ ? "payment.completed"
13
+ : status === "CANCELLED"
14
+ ? "payment.cancelled"
15
+ : "payment.failed";
16
+ return {
17
+ type,
18
+ data: {
19
+ provider: "payfast",
20
+ reference: payload.m_payment_id ?? "",
21
+ providerRef: payload.pf_payment_id,
22
+ amount: payload.amount_gross ? Number(payload.amount_gross) : undefined,
23
+ currency: payload.amount_gross ? "ZAR" : undefined,
24
+ raw: payload,
25
+ },
26
+ };
27
+ }
28
+ function mapOzowEvent(payload) {
29
+ const status = (payload.Status ?? "").toLowerCase();
30
+ const type = status === "complete"
31
+ ? "payment.completed"
32
+ : status === "cancelled"
33
+ ? "payment.cancelled"
34
+ : "payment.failed";
35
+ return {
36
+ type,
37
+ data: {
38
+ provider: "ozow",
39
+ reference: payload.TransactionReference ?? "",
40
+ providerRef: payload.TransactionId,
41
+ amount: payload.Amount ? Number(payload.Amount) : undefined,
42
+ currency: payload.CurrencyCode,
43
+ raw: payload,
44
+ },
45
+ };
46
+ }
47
+ function parsePayfastWebhook(input) {
48
+ const verified = verifyPayfastWebhook({
49
+ provider: "payfast",
50
+ rawBody: input.rawBody,
51
+ headers: input.headers,
52
+ secrets: {
53
+ passphrase: input.secrets.passphrase,
54
+ },
55
+ });
56
+ const payload = parseWebhookPayload(input.rawBody);
57
+ return {
58
+ isValid: verified.isValid,
59
+ event: mapPayfastEvent(payload),
60
+ raw: payload,
61
+ };
62
+ }
63
+ function parseOzowWebhook(input) {
64
+ const verified = verifyOzowWebhook({
65
+ provider: "ozow",
66
+ rawBody: input.rawBody,
67
+ headers: input.headers,
68
+ secrets: {
69
+ privateKey: input.secrets.privateKey,
70
+ },
71
+ });
72
+ const payload = parseWebhookPayload(input.rawBody);
73
+ return {
74
+ isValid: verified.isValid,
75
+ event: mapOzowEvent(payload),
76
+ raw: payload,
77
+ };
78
+ }
79
+ function parsePaystackWebhook(input) {
80
+ const signature = resolveHeader(input.headers, "x-paystack-signature");
81
+ const secretKey = input.secrets.paystackSecretKey ?? "";
82
+ const isValid = verifyPaystackWebhook(input.rawBody, signature, secretKey);
83
+ const rawText = Buffer.isBuffer(input.rawBody)
84
+ ? input.rawBody.toString("utf8")
85
+ : input.rawBody;
86
+ const payload = JSON.parse(rawText);
87
+ const event = mapPaystackEvent(payload);
88
+ return {
89
+ isValid,
90
+ event,
91
+ raw: payload,
92
+ };
93
+ }
94
+ function mapPaystackEvent(payload) {
95
+ const eventType = String(payload.event ?? "").toLowerCase();
96
+ const type = eventType === "charge.success" ? "payment.completed" : "payment.failed";
97
+ const data = payload.data ?? {};
98
+ return {
99
+ type,
100
+ data: {
101
+ provider: "paystack",
102
+ reference: String(data.reference ?? ""),
103
+ providerRef: data.id
104
+ ? String(data.id)
105
+ : undefined,
106
+ amount: data.amount
107
+ ? Number(data.amount)
108
+ : undefined,
109
+ currency: data.currency
110
+ ? String(data.currency)
111
+ : undefined,
112
+ raw: payload,
113
+ },
114
+ };
115
+ }
116
+ function resolveHeader(headers, key) {
117
+ if (!headers)
118
+ return undefined;
119
+ const lowerKey = key.toLowerCase();
120
+ for (const [headerKey, value] of Object.entries(headers)) {
121
+ if (headerKey.toLowerCase() !== lowerKey)
122
+ continue;
123
+ if (Array.isArray(value))
124
+ return value[0];
125
+ return value;
126
+ }
127
+ return undefined;
128
+ }
129
+ async function verifyOzowPaymentByReference(input) {
130
+ const siteCode = input.secrets.siteCode;
131
+ const apiKey = input.secrets.apiKey;
132
+ if (!siteCode || !apiKey) {
133
+ throw new Error("Ozow credentials missing for verification");
134
+ }
135
+ const baseUrl = input.testMode
136
+ ? "https://stagingapi.ozow.com"
137
+ : "https://api.ozow.com";
138
+ const url = new URL(`${baseUrl}/GetTransactionByReference`);
139
+ url.searchParams.set("siteCode", siteCode);
140
+ url.searchParams.set("transactionReference", input.reference);
141
+ if (input.testMode) {
142
+ url.searchParams.set("isTest", "true");
143
+ }
144
+ const response = await fetch(url.toString(), {
145
+ headers: {
146
+ ApiKey: apiKey,
147
+ Accept: "application/json",
148
+ },
149
+ });
150
+ const body = await response.json().catch(() => null);
151
+ if (!response.ok) {
152
+ throw new Error(`Ozow verify failed: ${response.statusText}`);
153
+ }
154
+ const transaction = Array.isArray(body) ? body[0] : null;
155
+ const statusRaw = String(transaction?.Status ?? "").toLowerCase();
156
+ const status = statusRaw === "complete"
157
+ ? "paid"
158
+ : statusRaw === "cancelled" || statusRaw === "error"
159
+ ? "failed"
160
+ : statusRaw
161
+ ? "pending"
162
+ : "unknown";
163
+ return {
164
+ provider: "ozow",
165
+ status,
166
+ providerRef: transaction?.TransactionId,
167
+ raw: body,
168
+ };
169
+ }
170
+ async function verifyPaystackPaymentByReference(input) {
171
+ const secretKey = input.secrets.paystackSecretKey;
172
+ if (!secretKey) {
173
+ throw new Error("Paystack secret key missing for verification");
174
+ }
175
+ return verifyPaystackPayment(input.reference, secretKey);
176
+ }
177
+ export const ozowAdapter = {
178
+ id: "ozow",
179
+ createPayment: async (input) => makeOzowPayment(input),
180
+ parseWebhook: (input) => parseOzowWebhook(input),
181
+ verifyPayment: (input) => verifyOzowPaymentByReference(input),
182
+ };
183
+ export const payfastAdapter = {
184
+ id: "payfast",
185
+ createPayment: async (input) => makePayfastPayment(input),
186
+ parseWebhook: (input) => parsePayfastWebhook(input),
187
+ };
188
+ export const paystackAdapter = {
189
+ id: "paystack",
190
+ createPayment: async (input) => makePaystackPayment(input),
191
+ parseWebhook: (input) => parsePaystackWebhook(input),
192
+ verifyPayment: (input) => verifyPaystackPaymentByReference(input),
193
+ };
194
+ export const providerAdapters = {
195
+ ozow: ozowAdapter,
196
+ payfast: payfastAdapter,
197
+ paystack: paystackAdapter,
198
+ };
@@ -0,0 +1,4 @@
1
+ import type { PaymentRequest, PaymentResponse, WebhookVerifyInput, WebhookVerifyResult } from "../types.js";
2
+ export declare function buildOzowHashCheck(payload: Record<string, string>, privateKey: string): string;
3
+ export declare function makeOzowPayment(input: PaymentRequest): Promise<PaymentResponse>;
4
+ export declare function verifyOzowWebhook(input: WebhookVerifyInput): WebhookVerifyResult;