@voyant-travel/plugin-netopia 0.104.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +80 -0
  3. package/dist/checkout.d.ts +4 -0
  4. package/dist/checkout.d.ts.map +1 -0
  5. package/dist/checkout.js +20 -0
  6. package/dist/client.d.ts +29 -0
  7. package/dist/client.d.ts.map +1 -0
  8. package/dist/client.js +221 -0
  9. package/dist/index.d.ts +9 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +6 -0
  12. package/dist/ipn.d.ts +42 -0
  13. package/dist/ipn.d.ts.map +1 -0
  14. package/dist/ipn.js +188 -0
  15. package/dist/notification-runtime.d.ts +13 -0
  16. package/dist/notification-runtime.d.ts.map +1 -0
  17. package/dist/notification-runtime.js +22 -0
  18. package/dist/plugin.d.ts +736 -0
  19. package/dist/plugin.d.ts.map +1 -0
  20. package/dist/plugin.js +231 -0
  21. package/dist/service-callback.d.ts +8 -0
  22. package/dist/service-callback.d.ts.map +1 -0
  23. package/dist/service-callback.js +200 -0
  24. package/dist/service-collect.d.ts +9 -0
  25. package/dist/service-collect.d.ts.map +1 -0
  26. package/dist/service-collect.js +70 -0
  27. package/dist/service-shared.d.ts +63 -0
  28. package/dist/service-shared.d.ts.map +1 -0
  29. package/dist/service-shared.js +40 -0
  30. package/dist/service-start.d.ts +6 -0
  31. package/dist/service-start.d.ts.map +1 -0
  32. package/dist/service-start.js +82 -0
  33. package/dist/service.d.ts +13 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +12 -0
  36. package/dist/types.d.ts +259 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +1 -0
  39. package/dist/validation.d.ts +666 -0
  40. package/dist/validation.d.ts.map +1 -0
  41. package/dist/validation.js +139 -0
  42. package/package.json +73 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for, the acceptance of support, warranty, indemnity, or
168
+ other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 PixelMakers Studio SRL
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # `@voyant-travel/plugin-netopia`
2
+
3
+ Netopia hosted-card payment adapter bundle for Voyant finance.
4
+
5
+ This package sits on top of `@voyant-travel/finance` and its `payment_sessions`
6
+ model. It does not replace finance state.
7
+
8
+ Architecturally, this package is primarily:
9
+
10
+ - a Netopia payment adapter
11
+ - a finance extension
12
+ - an optional packaged Hono bundle when an app wants one installable entrypoint
13
+
14
+ It starts a hosted Netopia checkout, stores provider references on the session,
15
+ and reconciles callback payloads back into Voyant payments, captures,
16
+ authorizations, invoices, and booking payment schedules.
17
+
18
+ ## Environment
19
+
20
+ The default finance extension resolves its runtime config from:
21
+
22
+ - `NETOPIA_URL`
23
+ - `NETOPIA_API_KEY`
24
+ - `NETOPIA_POS_SIGNATURE`
25
+ - `NETOPIA_NOTIFY_URL`
26
+ - `NETOPIA_REDIRECT_URL`
27
+
28
+ You can also override these programmatically via `createNetopiaFinanceExtension(options)`.
29
+
30
+ ## Routes
31
+
32
+ Mounted as a finance extension, the package exposes:
33
+
34
+ - `POST /providers/netopia/payment-sessions/:sessionId/start`
35
+ - `POST /providers/netopia/bookings/:bookingId/payment-schedules/:scheduleId/collect`
36
+ - `POST /providers/netopia/bookings/:bookingId/guarantees/:guaranteeId/collect`
37
+ - `POST /providers/netopia/invoices/:invoiceId/collect`
38
+ - `POST /providers/netopia/callback`
39
+ - `GET /providers/netopia/config`
40
+
41
+ ## Checkout integration
42
+
43
+ If you use Finance-owned checkout collection routes, the package also exports
44
+ `createNetopiaCheckoutStarter()`. That lets checkout create the payment session
45
+ and start the Netopia redirect flow in one request while keeping provider
46
+ startup optional in core checkout.
47
+
48
+ Because this is a finance extension, these routes mount under the finance module
49
+ path in the app.
50
+
51
+ ## Usage
52
+
53
+ ```ts
54
+ import { createNetopiaFinanceAdapter } from "@voyant-travel/plugin-netopia"
55
+
56
+ const netopiaFinanceExtension = createNetopiaFinanceAdapter()
57
+ ```
58
+
59
+ Then include the returned extension in `createApp({ extensions: [...] })`.
60
+
61
+ If you want the packaged distribution helper instead, use
62
+ `createNetopiaAdapterBundle()` or `netopiaHonoPlugin()`. Those are optional
63
+ distribution helpers over the adapter/extension surfaces above; the adapter and
64
+ finance extension remain the main runtime seams.
65
+
66
+ ## Flow
67
+
68
+ 1. Either create a finance `payment_session` yourself, or use one of the collect routes to create one from a booking schedule, guarantee, or invoice.
69
+ 2. Start the hosted Netopia checkout.
70
+ 3. Redirect the customer to the returned provider `paymentURL`.
71
+ 4. Optionally send a payment-link or invoice notification as part of the collect flow.
72
+ 5. Netopia calls the callback route.
73
+ 6. The adapter completes, fails, or updates the session in finance.
74
+
75
+ ## Notes
76
+
77
+ - Successful Netopia statuses default to `3` and `5`.
78
+ - In-flight statuses default to `1` and `15`.
79
+ - The callback path is idempotent for already-completed sessions.
80
+ - Amount/currency mismatch on a supposedly successful callback fails the session instead of silently accepting it.
@@ -0,0 +1,4 @@
1
+ import type { CheckoutPaymentStarter } from "@voyant-travel/finance/checkout";
2
+ import type { NetopiaRuntimeOptions } from "./types.js";
3
+ export declare function createNetopiaCheckoutStarter(runtimeOptions?: NetopiaRuntimeOptions): CheckoutPaymentStarter;
4
+ //# sourceMappingURL=checkout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../src/checkout.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAA;AAG7E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAGvD,wBAAgB,4BAA4B,CAC1C,cAAc,GAAE,qBAA0B,GACzC,sBAAsB,CA0BxB"}
@@ -0,0 +1,20 @@
1
+ import { startPaymentSession } from "./service-start.js";
2
+ import { netopiaStartPaymentSessionSchema } from "./validation.js";
3
+ export function createNetopiaCheckoutStarter(runtimeOptions = {}) {
4
+ return async ({ db, paymentSession, startProvider, bindings }) => {
5
+ const input = netopiaStartPaymentSessionSchema.parse(startProvider.payload ?? {});
6
+ const started = await startPaymentSession(db, paymentSession.id, input, runtimeOptions, undefined, bindings);
7
+ return {
8
+ provider: "netopia",
9
+ paymentSessionId: started.session.id,
10
+ redirectUrl: started.session.redirectUrl ?? started.providerResponse.payment?.paymentURL ?? null,
11
+ externalReference: started.session.externalReference ?? started.orderId,
12
+ providerSessionId: started.session.providerSessionId ?? null,
13
+ providerPaymentId: started.session.providerPaymentId ?? null,
14
+ response: {
15
+ orderId: started.orderId,
16
+ providerResponse: started.providerResponse,
17
+ },
18
+ };
19
+ };
20
+ }
@@ -0,0 +1,29 @@
1
+ import type { NetopiaFetch, NetopiaMode, NetopiaRuntimeOptions, NetopiaStartPaymentRequest, NetopiaStartPaymentResponse, NetopiaStatusRequest, NetopiaStatusResponse, ResolvedNetopiaRuntimeOptions } from "./types.js";
2
+ /**
3
+ * Known Netopia API base URLs. The client appends `/payment/card/start`
4
+ * (and any future paths) to whichever value is selected via `mode`. To
5
+ * point at a staging proxy or test mock — or if your tenant is provisioned
6
+ * on a non-default host — set `NETOPIA_URL` (or pass `apiUrl`) to override.
7
+ *
8
+ * The two hosts use *different* path conventions:
9
+ * - live host has a `/pay` prefix on every endpoint
10
+ * - sandbox host serves endpoints from the root
11
+ * Sourced from the protravel-v3 reference implementation.
12
+ */
13
+ export declare const NETOPIA_API_BASES: Record<NetopiaMode, string>;
14
+ export interface NetopiaClientApi {
15
+ startCardPayment(request: NetopiaStartPaymentRequest): Promise<NetopiaStartPaymentResponse>;
16
+ /**
17
+ * Authoritative payment-status lookup (`POST /operation/status`,
18
+ * merchant-authenticated via the API key). This is the server-to-server
19
+ * source of truth the callback handler verifies inbound IPNs against —
20
+ * the IPN body itself is never trusted for state transitions.
21
+ */
22
+ getPaymentStatus(request: NetopiaStatusRequest): Promise<NetopiaStatusResponse>;
23
+ }
24
+ export interface NetopiaClientOptions extends Pick<ResolvedNetopiaRuntimeOptions, "apiUrl" | "apiKey" | "resilience"> {
25
+ fetch?: NetopiaFetch;
26
+ }
27
+ export declare function resolveNetopiaRuntimeOptions(bindings: Record<string, unknown> | undefined, options?: NetopiaRuntimeOptions): ResolvedNetopiaRuntimeOptions;
28
+ export declare function createNetopiaClient(options: NetopiaClientOptions): NetopiaClientApi;
29
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,YAAY,EACZ,WAAW,EACX,qBAAqB,EACrB,0BAA0B,EAC1B,2BAA2B,EAC3B,oBAAoB,EACpB,qBAAqB,EACrB,6BAA6B,EAC9B,MAAM,YAAY,CAAA;AAGnB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAGzD,CAAA;AAED,MAAM,WAAW,gBAAgB;IAC/B,gBAAgB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAA;IAC3F;;;;;OAKG;IACH,gBAAgB,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAA;CAChF;AAED,MAAM,WAAW,oBACf,SAAQ,IAAI,CAAC,6BAA6B,EAAE,QAAQ,GAAG,QAAQ,GAAG,YAAY,CAAC;IAC/E,KAAK,CAAC,EAAE,YAAY,CAAA;CACrB;AA8CD,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC7C,OAAO,GAAE,qBAA0B,GAClC,6BAA6B,CAkD/B;AA0BD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG,gBAAgB,CAgGnF"}
package/dist/client.js ADDED
@@ -0,0 +1,221 @@
1
+ import { createCircuitBreaker, resilientFetch, } from "@voyant-travel/utils/resilience";
2
+ import { ZodError } from "zod";
3
+ import { resolvedNetopiaRuntimeOptionsSchema } from "./validation.js";
4
+ /**
5
+ * Known Netopia API base URLs. The client appends `/payment/card/start`
6
+ * (and any future paths) to whichever value is selected via `mode`. To
7
+ * point at a staging proxy or test mock — or if your tenant is provisioned
8
+ * on a non-default host — set `NETOPIA_URL` (or pass `apiUrl`) to override.
9
+ *
10
+ * The two hosts use *different* path conventions:
11
+ * - live host has a `/pay` prefix on every endpoint
12
+ * - sandbox host serves endpoints from the root
13
+ * Sourced from the protravel-v3 reference implementation.
14
+ */
15
+ export const NETOPIA_API_BASES = {
16
+ live: "https://secure.mobilpay.ro/pay",
17
+ sandbox: "https://secure.sandbox.netopia-payments.com",
18
+ };
19
+ /**
20
+ * One circuit breaker per Netopia base URL, module-level because clients
21
+ * are constructed per payment-start request and the breaker must outlive
22
+ * them to be useful (state is per-isolate, which is the right scope on
23
+ * edge runtimes).
24
+ */
25
+ const breakersByBaseUrl = new Map();
26
+ function breakerFor(apiUrl) {
27
+ let breaker = breakersByBaseUrl.get(apiUrl);
28
+ if (!breaker) {
29
+ breaker = createCircuitBreaker();
30
+ breakersByBaseUrl.set(apiUrl, breaker);
31
+ }
32
+ return breaker;
33
+ }
34
+ function createGlobalNetopiaFetch() {
35
+ if (typeof globalThis.fetch !== "function")
36
+ return undefined;
37
+ return (input, init) => globalThis.fetch(input, init);
38
+ }
39
+ function headersForPluginFetch(headers) {
40
+ if (!headers)
41
+ return {};
42
+ if (headers instanceof Headers || Array.isArray(headers)) {
43
+ return Object.fromEntries(new Headers(headers).entries());
44
+ }
45
+ const out = {};
46
+ for (const [key, value] of Object.entries(headers))
47
+ out[key] = String(value);
48
+ return out;
49
+ }
50
+ function asResilientFetch(fetchImpl) {
51
+ return async (input, init = {}) => {
52
+ const response = await fetchImpl(input instanceof Request ? input.url : String(input), {
53
+ method: init.method ?? "GET",
54
+ headers: headersForPluginFetch(init.headers),
55
+ ...(typeof init.body === "string" ? { body: init.body } : {}),
56
+ });
57
+ if (response instanceof Response)
58
+ return response;
59
+ return new Response(await response.text(), { status: response.status });
60
+ };
61
+ }
62
+ export function resolveNetopiaRuntimeOptions(bindings, options = {}) {
63
+ const env = bindings ?? {};
64
+ const apiUrlOverride = options.apiUrl ?? coerceString(env.NETOPIA_URL);
65
+ const mode = resolveMode(options.mode ?? coerceString(env.NETOPIA_MODE));
66
+ const apiUrl = apiUrlOverride ?? NETOPIA_API_BASES[mode];
67
+ const apiKey = options.apiKey ?? coerceString(env.NETOPIA_API_KEY);
68
+ const posSignature = options.posSignature ?? coerceString(env.NETOPIA_POS_SIGNATURE);
69
+ const notifyUrl = options.notifyUrl ?? coerceString(env.NETOPIA_NOTIFY_URL);
70
+ const redirectUrl = options.redirectUrl ?? coerceString(env.NETOPIA_REDIRECT_URL);
71
+ // PEM material is often stored as a single-line env var with literal `\n`
72
+ // escapes — normalize those back into real newlines.
73
+ const ipnPublicKey = (options.ipnPublicKey ?? coerceString(env.NETOPIA_IPN_PUBLIC_KEY))?.replaceAll("\\n", "\n");
74
+ const trustUnverifiedCallbacks = options.trustUnverifiedCallbacks ?? coerceBoolean(env.NETOPIA_TRUST_UNVERIFIED_CALLBACKS);
75
+ if (!apiKey)
76
+ throw new Error("Missing Netopia config: NETOPIA_API_KEY");
77
+ if (!posSignature)
78
+ throw new Error("Missing Netopia config: NETOPIA_POS_SIGNATURE");
79
+ if (!notifyUrl)
80
+ throw new Error("Missing Netopia config: NETOPIA_NOTIFY_URL");
81
+ if (!redirectUrl)
82
+ throw new Error("Missing Netopia config: NETOPIA_REDIRECT_URL");
83
+ try {
84
+ return resolvedNetopiaRuntimeOptionsSchema.parse({
85
+ apiUrl,
86
+ apiKey,
87
+ posSignature,
88
+ notifyUrl,
89
+ redirectUrl,
90
+ emailTemplate: options.emailTemplate,
91
+ language: options.language,
92
+ successStatuses: options.successStatuses,
93
+ processingStatuses: options.processingStatuses,
94
+ ipnPublicKey,
95
+ trustUnverifiedCallbacks,
96
+ fetch: options.fetch,
97
+ resilience: options.resilience,
98
+ });
99
+ }
100
+ catch (error) {
101
+ if (error instanceof ZodError) {
102
+ const detail = error.issues
103
+ .map((issue) => {
104
+ const path = issue.path.join(".") || "runtimeOptions";
105
+ return `${path}: ${issue.message}`;
106
+ })
107
+ .join("; ");
108
+ throw new Error(`Invalid Netopia runtime options: ${detail}`);
109
+ }
110
+ throw error;
111
+ }
112
+ }
113
+ function coerceString(value) {
114
+ return typeof value === "string" && value.length > 0 ? value : undefined;
115
+ }
116
+ function coerceBoolean(value) {
117
+ if (typeof value === "boolean")
118
+ return value;
119
+ if (typeof value === "string") {
120
+ const normalized = value.trim().toLowerCase();
121
+ if (normalized === "1" || normalized === "true")
122
+ return true;
123
+ if (normalized === "0" || normalized === "false" || normalized === "")
124
+ return false;
125
+ }
126
+ return undefined;
127
+ }
128
+ function resolveMode(raw) {
129
+ if (raw === "live" || raw === "sandbox")
130
+ return raw;
131
+ if (raw !== undefined) {
132
+ throw new Error(`Invalid NETOPIA_MODE: ${raw} (expected "sandbox" or "live")`);
133
+ }
134
+ // Default to sandbox so a half-configured production deploy fails into
135
+ // the safer environment instead of charging real cards.
136
+ return "sandbox";
137
+ }
138
+ export function createNetopiaClient(options) {
139
+ const apiUrl = options.apiUrl.replace(/\/$/, "");
140
+ const fetchImpl = options.fetch ?? createGlobalNetopiaFetch();
141
+ const breaker = options.resilience?.breaker ?? breakerFor(apiUrl);
142
+ // Payments get a longer per-attempt ceiling than the 10s default used for
143
+ // non-payment upstreams; no stricter timeout existed before this.
144
+ const timeoutMs = options.resilience?.timeoutMs ?? 15_000;
145
+ async function request(method, path, body) {
146
+ if (!fetchImpl) {
147
+ throw new Error("Netopia client requires a fetch implementation");
148
+ }
149
+ const response = await resilientFetch(`${apiUrl}${path}`, {
150
+ method,
151
+ headers: {
152
+ Authorization: options.apiKey,
153
+ "Content-Type": "application/json",
154
+ Accept: "application/json",
155
+ },
156
+ body: body === undefined ? undefined : JSON.stringify(body),
157
+ }, {
158
+ timeoutMs,
159
+ breaker,
160
+ // NEVER retry: payment initiation moves money and Netopia exposes no
161
+ // idempotency keys — a duplicate charge is worse than a failed
162
+ // checkout the customer can retry. `retryOn: () => false` also
163
+ // surfaces 5xx responses so the rich error mapping below keeps the
164
+ // upstream status + body (the breaker still records the failure).
165
+ retry: { retryOn: () => false },
166
+ fetchImpl: asResilientFetch(fetchImpl),
167
+ });
168
+ let text = "";
169
+ let json = null;
170
+ try {
171
+ text = await response.text();
172
+ json = text ? JSON.parse(text) : null;
173
+ }
174
+ catch {
175
+ // Surface raw text in the thrown error below.
176
+ }
177
+ return { ok: response.ok, status: response.status, json, text };
178
+ }
179
+ return {
180
+ async startCardPayment(requestBody) {
181
+ const res = await request("POST", "/payment/card/start", requestBody);
182
+ const json = (res.json ?? {});
183
+ // Netopia quirk (per protravel-v3 reference): error code 101 means
184
+ // "redirect customer to payment page" — it's success-with-redirect,
185
+ // not a failure. The API sometimes omits `paymentURL` in this case;
186
+ // upstream callers fall back to other fields on the session.
187
+ if (json.error && String(json.error.code) === "101") {
188
+ return json;
189
+ }
190
+ if (!res.ok || json.error) {
191
+ const detail = json.error?.message ??
192
+ (res.status === 404
193
+ ? `Endpoint not found at ${apiUrl}/payment/card/start. Verify NETOPIA_MODE/NETOPIA_URL.`
194
+ : stripHtml(res.text).slice(0, 200));
195
+ throw new Error(`Netopia start payment failed (${json.error?.code ?? res.status}): ${detail}`);
196
+ }
197
+ return json;
198
+ },
199
+ async getPaymentStatus(requestBody) {
200
+ // Read-only verification call. Still a single attempt — the IPN
201
+ // retry loop (we answer the callback with a retryable error when
202
+ // this fails) is the recovery mechanism, not client-side retries.
203
+ const res = await request("POST", "/operation/status", requestBody);
204
+ const json = (res.json ?? {});
205
+ if (!res.ok || json.error) {
206
+ const detail = json.error?.message ??
207
+ (res.status === 404
208
+ ? `Endpoint not found at ${apiUrl}/operation/status. Verify NETOPIA_MODE/NETOPIA_URL.`
209
+ : stripHtml(res.text).slice(0, 200));
210
+ throw new Error(`Netopia status lookup failed (${json.error?.code ?? res.status}): ${detail}`);
211
+ }
212
+ return json;
213
+ },
214
+ };
215
+ }
216
+ function stripHtml(text) {
217
+ return text
218
+ .replace(/<[^>]+>/g, "")
219
+ .replace(/\s+/g, " ")
220
+ .trim();
221
+ }
@@ -0,0 +1,9 @@
1
+ export { createNetopiaCheckoutStarter } from "./checkout.js";
2
+ export { createNetopiaClient, NETOPIA_API_BASES, type NetopiaClientApi, type NetopiaClientOptions, resolveNetopiaRuntimeOptions, } from "./client.js";
3
+ export type { NetopiaNotificationRuntime, NetopiaNotificationRuntimeOptions, } from "./notification-runtime.js";
4
+ export { buildNetopiaNotificationRuntime } from "./notification-runtime.js";
5
+ export { createNetopiaFinanceExtension, createNetopiaFinanceExtension as createNetopiaFinanceAdapter, createNetopiaFinanceRoutes, NETOPIA_RUNTIME_CONTAINER_KEY, netopiaFinanceExtension, netopiaHonoBundle, netopiaHonoPlugin as createNetopiaAdapterBundle, netopiaHonoPlugin, } from "./plugin.js";
6
+ export { deriveNetopiaOrderId, mapNetopiaPaymentStatus, type NetopiaCallbackResult, type NetopiaCollectPaymentResult, type NetopiaStartPaymentResult, netopiaService, } from "./service.js";
7
+ export type { NetopiaBillingAddress, NetopiaBrowserData, NetopiaFetch, NetopiaInstallments, NetopiaMode, NetopiaPaymentInstrument, NetopiaPaymentOptions, NetopiaProductLine, NetopiaRuntimeOptions, NetopiaStartPaymentInput, NetopiaStartPaymentRequest, NetopiaStartPaymentResponse, NetopiaWebhookPayload, ResolvedNetopiaRuntimeOptions, } from "./types.js";
8
+ export { netopiaBillingAddressSchema, netopiaBrowserDataSchema, netopiaCollectBookingGuaranteeSchema, netopiaCollectBookingScheduleSchema, netopiaCollectInvoiceSchema, netopiaInstallmentsSchema, netopiaPaymentInstrumentSchema, netopiaPaymentOptionsSchema, netopiaProductLineSchema, netopiaRuntimeOptionsSchema, netopiaStartPaymentSessionSchema, netopiaWebhookPayloadSchema, resolvedNetopiaRuntimeOptionsSchema, } from "./validation.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAA;AAC5D,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,4BAA4B,GAC7B,MAAM,aAAa,CAAA;AACpB,YAAY,EACV,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAA;AAC3E,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,IAAI,2BAA2B,EAC5D,0BAA0B,EAC1B,6BAA6B,EAC7B,uBAAuB,EACvB,iBAAiB,EACjB,iBAAiB,IAAI,0BAA0B,EAC/C,iBAAiB,GAClB,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,oBAAoB,EACpB,uBAAuB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,yBAAyB,EAC9B,cAAc,GACf,MAAM,cAAc,CAAA;AACrB,YAAY,EACV,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,WAAW,EACX,wBAAwB,EACxB,qBAAqB,EACrB,kBAAkB,EAClB,qBAAqB,EACrB,wBAAwB,EACxB,0BAA0B,EAC1B,2BAA2B,EAC3B,qBAAqB,EACrB,6BAA6B,GAC9B,MAAM,YAAY,CAAA;AACnB,OAAO,EACL,2BAA2B,EAC3B,wBAAwB,EACxB,oCAAoC,EACpC,mCAAmC,EACnC,2BAA2B,EAC3B,yBAAyB,EACzB,8BAA8B,EAC9B,2BAA2B,EAC3B,wBAAwB,EACxB,2BAA2B,EAC3B,gCAAgC,EAChC,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { createNetopiaCheckoutStarter } from "./checkout.js";
2
+ export { createNetopiaClient, NETOPIA_API_BASES, resolveNetopiaRuntimeOptions, } from "./client.js";
3
+ export { buildNetopiaNotificationRuntime } from "./notification-runtime.js";
4
+ export { createNetopiaFinanceExtension, createNetopiaFinanceExtension as createNetopiaFinanceAdapter, createNetopiaFinanceRoutes, NETOPIA_RUNTIME_CONTAINER_KEY, netopiaFinanceExtension, netopiaHonoBundle, netopiaHonoPlugin as createNetopiaAdapterBundle, netopiaHonoPlugin, } from "./plugin.js";
5
+ export { deriveNetopiaOrderId, mapNetopiaPaymentStatus, netopiaService, } from "./service.js";
6
+ export { netopiaBillingAddressSchema, netopiaBrowserDataSchema, netopiaCollectBookingGuaranteeSchema, netopiaCollectBookingScheduleSchema, netopiaCollectInvoiceSchema, netopiaInstallmentsSchema, netopiaPaymentInstrumentSchema, netopiaPaymentOptionsSchema, netopiaProductLineSchema, netopiaRuntimeOptionsSchema, netopiaStartPaymentSessionSchema, netopiaWebhookPayloadSchema, resolvedNetopiaRuntimeOptionsSchema, } from "./validation.js";
package/dist/ipn.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Netopia v2 IPN signature verification.
3
+ *
4
+ * Netopia v2 signs every IPN callback with a JWT carried in the
5
+ * `Verification-token` HTTP header (see the official SDKs, e.g.
6
+ * github.com/netopiapayments/go-sdk `VerifyIPN`):
7
+ *
8
+ * - signed with RSA (RS256/RS384/RS512) using NETOPIA's platform key;
9
+ * merchants receive the platform certificate (PEM) to verify against
10
+ * - `iss` must be `"NETOPIA Payments"`
11
+ * - `aud` must contain the merchant's POS signature
12
+ * - `sub` is the base64 (standard alphabet) SHA-512 digest of the raw
13
+ * request body, binding the token to this exact payload
14
+ *
15
+ * This module implements that verification using only Web Crypto, so it
16
+ * runs on Cloudflare Workers (no Node `crypto`). It accepts the key as
17
+ * either a `CERTIFICATE` PEM (the SubjectPublicKeyInfo is extracted with a
18
+ * minimal DER walk) or a `PUBLIC KEY` (SPKI) PEM.
19
+ */
20
+ export type NetopiaIpnVerification = {
21
+ ok: true;
22
+ } | {
23
+ ok: false;
24
+ reason: string;
25
+ };
26
+ export interface VerifyNetopiaIpnInput {
27
+ /** Value of the `Verification-token` header. */
28
+ token: string | null | undefined;
29
+ /** Raw (unparsed) request body, exactly as received. */
30
+ rawBody: string;
31
+ /** The merchant POS signature the token's `aud` must match. */
32
+ posSignature: string;
33
+ /** PEM: NETOPIA platform certificate or its public key. */
34
+ publicKeyPem: string;
35
+ }
36
+ export declare function verifyNetopiaIpnToken(input: VerifyNetopiaIpnInput): Promise<NetopiaIpnVerification>;
37
+ /**
38
+ * Constant-time string comparison (over UTF-16 code units). Length still
39
+ * leaks, which is fine here — lengths of digests/POS signatures are public.
40
+ */
41
+ export declare function timingSafeStringEqual(a: string, b: string): boolean;
42
+ //# sourceMappingURL=ipn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipn.d.ts","sourceRoot":"","sources":["../src/ipn.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,MAAM,sBAAsB,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAEjF,MAAM,WAAW,qBAAqB;IACpC,gDAAgD;IAChD,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;IAChC,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAA;IACf,+DAA+D;IAC/D,YAAY,EAAE,MAAM,CAAA;IACpB,2DAA2D;IAC3D,YAAY,EAAE,MAAM,CAAA;CACrB;AAQD,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,sBAAsB,CAAC,CAmEjC;AAUD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAOnE"}