@tly-pay/vendure-plugin 0.0.0-stage → 1.0.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +192 -2
  4. package/assets/coins/arb.svg +10 -0
  5. package/assets/coins/base.svg +4 -0
  6. package/assets/coins/bln.svg +4 -0
  7. package/assets/coins/bnb.svg +13 -0
  8. package/assets/coins/btc.svg +1 -0
  9. package/assets/coins/busd.svg +7 -0
  10. package/assets/coins/coin.svg +1 -0
  11. package/assets/coins/dai.svg +1 -0
  12. package/assets/coins/doge.svg +109 -0
  13. package/assets/coins/eth.svg +10 -0
  14. package/assets/coins/jst.svg +11 -0
  15. package/assets/coins/link.svg +4 -0
  16. package/assets/coins/ltc.svg +4 -0
  17. package/assets/coins/op.svg +12 -0
  18. package/assets/coins/pol.svg +11 -0
  19. package/assets/coins/shib.svg +18 -0
  20. package/assets/coins/sol.svg +15 -0
  21. package/assets/coins/sun.svg +71 -0
  22. package/assets/coins/trx.svg +4 -0
  23. package/assets/coins/uni.svg +10 -0
  24. package/assets/coins/usdc.svg +6 -0
  25. package/assets/coins/usdd.svg +18 -0
  26. package/assets/coins/usdt.svg +1 -0
  27. package/assets/coins/wbtc.svg +16 -0
  28. package/assets/coins/weth.svg +17 -0
  29. package/assets/tly-pay-mark.svg +31 -0
  30. package/dashboard/api.ts +167 -0
  31. package/dashboard/appearance.tsx +253 -0
  32. package/dashboard/banner.tsx +72 -0
  33. package/dashboard/i18n/en.po +584 -0
  34. package/dashboard/index.tsx +33 -0
  35. package/dashboard/logic.ts +219 -0
  36. package/dashboard/messages.tsx +90 -0
  37. package/dashboard/notice.tsx +15 -0
  38. package/dashboard/order-block.tsx +21 -0
  39. package/dashboard/orders.tsx +246 -0
  40. package/dashboard/page.tsx +174 -0
  41. package/dashboard/settings.tsx +186 -0
  42. package/dashboard/use-connect.ts +46 -0
  43. package/dist/api.d.ts +169 -0
  44. package/dist/api.js +541 -0
  45. package/dist/client-ref.d.ts +75 -0
  46. package/dist/client-ref.js +165 -0
  47. package/dist/connect-flow.d.ts +65 -0
  48. package/dist/connect-flow.js +177 -0
  49. package/dist/connection-check.d.ts +28 -0
  50. package/dist/connection-check.js +49 -0
  51. package/dist/connection.d.ts +140 -0
  52. package/dist/connection.js +361 -0
  53. package/dist/contracts.d.ts +66 -0
  54. package/dist/contracts.js +151 -0
  55. package/dist/creation-service.d.ts +136 -0
  56. package/dist/creation-service.js +242 -0
  57. package/dist/handler.d.ts +13 -0
  58. package/dist/handler.js +45 -0
  59. package/dist/hosted-checkout.d.ts +3 -0
  60. package/dist/hosted-checkout.js +25 -0
  61. package/dist/index.d.ts +11 -0
  62. package/dist/index.js +32 -0
  63. package/dist/ownership.d.ts +38 -0
  64. package/dist/ownership.js +38 -0
  65. package/dist/payment-sync.d.ts +45 -0
  66. package/dist/payment-sync.js +111 -0
  67. package/dist/persistence.d.ts +104 -0
  68. package/dist/persistence.js +405 -0
  69. package/dist/plugin.d.ts +26 -0
  70. package/dist/plugin.js +112 -0
  71. package/dist/public-api.d.ts +56 -0
  72. package/dist/public-api.js +221 -0
  73. package/dist/records.d.ts +53 -0
  74. package/dist/records.js +109 -0
  75. package/dist/release-config.d.ts +55 -0
  76. package/dist/release-config.js +107 -0
  77. package/dist/release-config.json +15 -0
  78. package/dist/secret-box.d.ts +19 -0
  79. package/dist/secret-box.js +65 -0
  80. package/dist/service.d.ts +267 -0
  81. package/dist/service.js +788 -0
  82. package/dist/signed-webhook.d.ts +67 -0
  83. package/dist/signed-webhook.js +119 -0
  84. package/dist/storefront/checkout.d.mts +86 -0
  85. package/dist/storefront/checkout.mjs +149 -0
  86. package/package.json +97 -4
@@ -0,0 +1,136 @@
1
+ import { Connection } from "./connection";
2
+ import { PaymentView } from "./contracts";
3
+ import { PublicApiClient } from "./public-api";
4
+ import { ReleaseConfig } from "./release-config";
5
+ /**
6
+ * One durable Payment creation intent. It is stored before `POST /v1/payments` and keeps the exact
7
+ * request body and Idempotency-Key, so replaying it into the same Store returns the same Payment.
8
+ */
9
+ export type PaymentAssociation = {
10
+ id: string;
11
+ channelToken: string;
12
+ orderCode: string;
13
+ paymentMethodCode: string;
14
+ attemptNo: number;
15
+ storeId: string;
16
+ idempotencyKey: string;
17
+ requestHash: string;
18
+ requestBody: string;
19
+ state: "creating" | "bound" | "failed";
20
+ err: string | null;
21
+ createdAt: Date;
22
+ /** Start of the latest recovery replay, null until recovery first replays the intent. */
23
+ lastAttemptAt: Date | null;
24
+ paymentId: string | null;
25
+ hostedUrl: string | null;
26
+ status: PaymentView["status"] | null;
27
+ statusVersion: number;
28
+ };
29
+ export type AssociationInput = Pick<PaymentAssociation, "channelToken" | "orderCode" | "paymentMethodCode" | "attemptNo" | "storeId" | "idempotencyKey" | "requestHash" | "requestBody">;
30
+ export interface AssociationStore {
31
+ /**
32
+ * Returns the intent of this Channel, Order, PaymentMethod and attempt with the same requestHash
33
+ * unless it failed; otherwise commits the input as a new `creating` intent and returns it.
34
+ */
35
+ reserve(input: AssociationInput): Promise<PaymentAssociation>;
36
+ /**
37
+ * Sets the Payment ID, Hosted URL and state `bound` only where the Payment ID is null or equal, and
38
+ * returns the stored row. A different stored Payment ID stays unchanged.
39
+ */
40
+ bindPayment(id: string, paymentId: string, hostedUrl: string): Promise<PaymentAssociation>;
41
+ /** Sets state `failed` and err on a `creating` intent. */
42
+ markFailed(id: string, err: string): Promise<void>;
43
+ /** Sets lastAttemptAt of a `creating` intent before recovery replays it. */
44
+ recordAttempt(id: string, at: Date): Promise<void>;
45
+ /** Stores the authoritative status only when its version is newer, and returns the stored row. */
46
+ recordAuthority(id: string, view: PaymentView): Promise<PaymentAssociation>;
47
+ /** The association bound to this Payment ID, or null. */
48
+ findByPaymentId(paymentId: string): Promise<PaymentAssociation | null>;
49
+ /** Every intent of this Channel and Order, newest first. */
50
+ findOrderIntents(channelToken: string, orderCode: string): Promise<PaymentAssociation[]>;
51
+ /** `creating` intents whose order code equals this order_ref, newest first. */
52
+ findCreatingIntents(orderCode: string): Promise<PaymentAssociation[]>;
53
+ /**
54
+ * One bounded batch of `creating` intents created before this time, least recently attempted
55
+ * first: never attempted (lastAttemptAt null) first, then oldest lastAttemptAt, then oldest
56
+ * createdAt. Intents that keep failing (for example on 401) then rotate behind the others.
57
+ */
58
+ findRecoverable(createdBefore: Date): Promise<PaymentAssociation[]>;
59
+ }
60
+ export type CheckoutMode = "embedded" | "hosted";
61
+ export type CreatePaymentInput = {
62
+ channelToken: string;
63
+ orderCode: string;
64
+ paymentMethodCode: string;
65
+ amountMinor: number;
66
+ currencyCode: string;
67
+ /** Mode of a new intent; an Order that already has a reusable intent keeps the mode it was created with. */
68
+ checkoutMode: CheckoutMode;
69
+ /** Storefront page the Widget returns to after payment; required for embedded mode. */
70
+ returnUrl: string | null;
71
+ };
72
+ /** The connected Store facts a Payment is created against. */
73
+ export type StoreBinding = Pick<Connection, "storeId" | "sourceCurrency" | "sourceDecimals" | "merchantDomain">;
74
+ /** Recovery of a webhook's unknown Payment: bound to it, retry later, or not created here. */
75
+ export type EventRecovery = {
76
+ outcome: "bound";
77
+ association: PaymentAssociation;
78
+ } | {
79
+ outcome: "pending";
80
+ } | {
81
+ outcome: "none";
82
+ };
83
+ /** The storefront's input cannot create a Payment; `code` is a stable, non-sensitive reason. */
84
+ export declare class CheckoutRejected extends TypeError {
85
+ readonly code: string;
86
+ constructor(code: string);
87
+ }
88
+ export declare function amountRaw(amountMinor: number, decimals: number): string;
89
+ /** Whether a stored creation body asked for embedded checkout (it carries `checkout_origin`). */
90
+ export declare function embeddedBody(requestBody: string): boolean;
91
+ /**
92
+ * The HTTPS storefront page the Widget returns to: port 443, no credentials or fragment. Its Origin
93
+ * becomes `checkout_origin`. The website registered on the TLY Pay Store is optional and does not
94
+ * limit the storefront: TLY Pay accepts any HTTPS checkout origin and records it on the Payment.
95
+ */
96
+ export declare function validReturnUrl(value: string | null): URL;
97
+ export declare class TlyPayCreationService {
98
+ private readonly api;
99
+ private readonly associations;
100
+ private readonly options;
101
+ private readonly clientRef;
102
+ private readonly store;
103
+ constructor(api: PublicApiClient, associations: AssociationStore, options: Pick<ReleaseConfig, "widgetOrigin" | "paymentRecoveryDelaySecs">, clientRef: string, store: () => Promise<StoreBinding>);
104
+ /**
105
+ * Returns the Order's Payment. A reusable intent of the connected Store for the same payment method,
106
+ * currency and amount, not failed, expired or cancelled, is replayed with its own body and key (so it
107
+ * keeps its checkout mode) and checked against its own currency and amount, also after the TLY Store
108
+ * changed its pricing currency. Only a new Payment needs `newPaymentAllowed` (`checkout_unavailable`)
109
+ * and the Store's current currency (`currency_mismatch`); its intent is committed before
110
+ * `POST /v1/payments`.
111
+ */
112
+ createOrRecover(input: CreatePaymentInput, newPaymentAllowed?: () => Promise<boolean>): Promise<PaymentAssociation & {
113
+ view: PaymentView;
114
+ }>;
115
+ private reserve;
116
+ /**
117
+ * Webhook trigger: replays this order_ref's `creating` intents, newest first, until one binds to
118
+ * the event's Payment. A transient replay failure answers `pending` so TLY Pay retries the event.
119
+ */
120
+ recoverForEvent(orderRef: string, paymentId: string): Promise<EventRecovery>;
121
+ /**
122
+ * Scheduled trigger: replays one batch of `creating` intents older than the recovery delay. The
123
+ * host runs it from a Vendure ScheduledTask; intents still pending are picked up by a later run.
124
+ */
125
+ recoverDue(now?: Date): Promise<{
126
+ bound: number;
127
+ failed: number;
128
+ pending: number;
129
+ }>;
130
+ private replay;
131
+ /**
132
+ * Sends the intent's stored request. 2xx binds, a definitive rejection fails the intent, and any
133
+ * other outcome leaves it `creating` with its key for a later replay.
134
+ */
135
+ private submit;
136
+ }
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TlyPayCreationService = exports.CheckoutRejected = void 0;
4
+ exports.amountRaw = amountRaw;
5
+ exports.embeddedBody = embeddedBody;
6
+ exports.validReturnUrl = validReturnUrl;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const core_1 = require("@vendure/core");
9
+ const contracts_1 = require("./contracts");
10
+ const hosted_checkout_1 = require("./hosted-checkout");
11
+ const public_api_1 = require("./public-api");
12
+ const LOG_CONTEXT = "TlyPay";
13
+ /** The storefront's input cannot create a Payment; `code` is a stable, non-sensitive reason. */
14
+ class CheckoutRejected extends TypeError {
15
+ code;
16
+ constructor(code) {
17
+ super(`TLY Pay checkout rejected: ${code}`);
18
+ this.code = code;
19
+ }
20
+ }
21
+ exports.CheckoutRejected = CheckoutRejected;
22
+ function amountRaw(amountMinor, decimals) {
23
+ if (!Number.isSafeInteger(amountMinor) || amountMinor < 1 || decimals < 0 || decimals > 18) {
24
+ throw new TypeError("Vendure amount is invalid");
25
+ }
26
+ return BigInt(amountMinor).toString();
27
+ }
28
+ /** Whether a stored creation body asked for embedded checkout (it carries `checkout_origin`). */
29
+ function embeddedBody(requestBody) {
30
+ try {
31
+ const body = JSON.parse(requestBody);
32
+ return body !== null && typeof body === "object" && typeof body.checkout_origin === "string";
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * The HTTPS storefront page the Widget returns to: port 443, no credentials or fragment. Its Origin
40
+ * becomes `checkout_origin`. The website registered on the TLY Pay Store is optional and does not
41
+ * limit the storefront: TLY Pay accepts any HTTPS checkout origin and records it on the Payment.
42
+ */
43
+ function validReturnUrl(value) {
44
+ let url;
45
+ try {
46
+ url = new URL(value ?? "");
47
+ }
48
+ catch {
49
+ throw new CheckoutRejected("return_url_invalid");
50
+ }
51
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || value.length > 2048
52
+ || url.port !== "" && url.port !== "443") {
53
+ throw new CheckoutRejected("return_url_invalid");
54
+ }
55
+ return url;
56
+ }
57
+ const CLOSED_STATUSES = new Set(["expired", "cancelled"]);
58
+ class TlyPayCreationService {
59
+ api;
60
+ associations;
61
+ options;
62
+ clientRef;
63
+ store;
64
+ constructor(api, associations, options, clientRef, store) {
65
+ this.api = api;
66
+ this.associations = associations;
67
+ this.options = options;
68
+ this.clientRef = clientRef;
69
+ this.store = store;
70
+ if (!contracts_1.CLIENT_REF.test(clientRef))
71
+ throw new TypeError("TLY Pay client_ref is invalid");
72
+ }
73
+ /**
74
+ * Returns the Order's Payment. A reusable intent of the connected Store for the same payment method,
75
+ * currency and amount, not failed, expired or cancelled, is replayed with its own body and key (so it
76
+ * keeps its checkout mode) and checked against its own currency and amount, also after the TLY Store
77
+ * changed its pricing currency. Only a new Payment needs `newPaymentAllowed` (`checkout_unavailable`)
78
+ * and the Store's current currency (`currency_mismatch`); its intent is committed before
79
+ * `POST /v1/payments`.
80
+ */
81
+ async createOrRecover(input, newPaymentAllowed = async () => true) {
82
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(input.channelToken)
83
+ || !/^\S{1,128}$/.test(input.orderCode)
84
+ || !/^[a-z0-9_-]{1,64}$/.test(input.paymentMethodCode)
85
+ || !/^[A-Z]{3}$/.test(input.currencyCode)) {
86
+ throw new TypeError("Vendure Payment association is invalid");
87
+ }
88
+ const store = await this.store();
89
+ const raw = amountRaw(input.amountMinor, store.sourceDecimals);
90
+ const intents = await this.associations.findOrderIntents(input.channelToken, input.orderCode);
91
+ let association = intents.find((intent) => intent.state !== "failed" && intent.storeId === store.storeId
92
+ && intent.paymentMethodCode === input.paymentMethodCode
93
+ && !(intent.status !== null && CLOSED_STATUSES.has(intent.status))
94
+ && sameSource(intent.requestBody, input.currencyCode, raw));
95
+ if (association === undefined) {
96
+ if (!await newPaymentAllowed())
97
+ throw new CheckoutRejected("checkout_unavailable");
98
+ if (input.currencyCode !== store.sourceCurrency)
99
+ throw new CheckoutRejected("currency_mismatch");
100
+ association = await this.reserve(input, store, raw, intents.length + 1);
101
+ }
102
+ const bound = association.state === "bound" ? association : await this.submit(association);
103
+ if (bound === "failed")
104
+ throw new CheckoutRejected("payment_rejected");
105
+ if (bound === "pending")
106
+ throw new Error("TLY Pay Payment creation is pending");
107
+ const paymentId = bound.paymentId;
108
+ if (paymentId === null)
109
+ throw new TypeError("Vendure Payment association was not persisted");
110
+ const view = await this.api.getPayment(paymentId);
111
+ // An intent does not store the decimals; the Store's apply while it prices in the intent's currency.
112
+ const decimals = input.currencyCode === store.sourceCurrency ? store.sourceDecimals : null;
113
+ if (view.orderRef !== input.orderCode || view.clientRef !== this.clientRef || view.sourceAmount.currency !== input.currencyCode
114
+ || view.sourceAmount.amountRaw !== raw || decimals !== null && view.sourceAmount.decimals !== decimals) {
115
+ throw new TypeError("TLY Payment differs from Vendure order");
116
+ }
117
+ const current = await this.associations.recordAuthority(bound.id, view);
118
+ if (current.paymentId !== paymentId || current.hostedUrl !== (0, hosted_checkout_1.hostedCheckoutUrl)(this.options.widgetOrigin, paymentId)) {
119
+ throw new TypeError("Vendure Payment association was not persisted");
120
+ }
121
+ return { ...current, view };
122
+ }
123
+ async reserve(input, store, raw, attemptNo) {
124
+ const body = {
125
+ order_ref: input.orderCode,
126
+ client_ref: this.clientRef,
127
+ source_amount: { kind: "fiat", currency: store.sourceCurrency, amount_raw: raw },
128
+ };
129
+ if (input.checkoutMode === "embedded") {
130
+ const returnUrl = validReturnUrl(input.returnUrl);
131
+ body.checkout_origin = returnUrl.origin;
132
+ body.return_url = returnUrl.toString();
133
+ }
134
+ const requestBody = JSON.stringify(body);
135
+ const requestHash = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify([
136
+ store.storeId, input.channelToken, input.orderCode, input.paymentMethodCode, attemptNo, requestBody,
137
+ ])).digest("hex");
138
+ const association = await this.associations.reserve({
139
+ channelToken: input.channelToken,
140
+ orderCode: input.orderCode,
141
+ paymentMethodCode: input.paymentMethodCode,
142
+ attemptNo,
143
+ storeId: store.storeId,
144
+ idempotencyKey: `vendure_${(0, node_crypto_1.randomBytes)(32).toString("base64url")}`,
145
+ requestHash,
146
+ requestBody,
147
+ });
148
+ if (association.requestHash !== requestHash || association.requestBody !== requestBody
149
+ || association.storeId !== store.storeId || association.state === "failed") {
150
+ throw new TypeError("Vendure Payment association changed");
151
+ }
152
+ return association;
153
+ }
154
+ /**
155
+ * Webhook trigger: replays this order_ref's `creating` intents, newest first, until one binds to
156
+ * the event's Payment. A transient replay failure answers `pending` so TLY Pay retries the event.
157
+ */
158
+ async recoverForEvent(orderRef, paymentId) {
159
+ const intents = await this.associations.findCreatingIntents(orderRef);
160
+ if (intents.length === 0)
161
+ return { outcome: "none" };
162
+ let storeId;
163
+ try {
164
+ storeId = (await this.store()).storeId;
165
+ }
166
+ catch {
167
+ return { outcome: "pending" };
168
+ }
169
+ let pending = false;
170
+ for (const intent of intents) {
171
+ const result = await this.replay(intent, storeId, new Date());
172
+ if (result === "pending")
173
+ pending = true;
174
+ else if (result !== "failed" && result.paymentId === paymentId)
175
+ return { outcome: "bound", association: result };
176
+ }
177
+ return pending ? { outcome: "pending" } : { outcome: "none" };
178
+ }
179
+ /**
180
+ * Scheduled trigger: replays one batch of `creating` intents older than the recovery delay. The
181
+ * host runs it from a Vendure ScheduledTask; intents still pending are picked up by a later run.
182
+ */
183
+ async recoverDue(now = new Date()) {
184
+ const counts = { bound: 0, failed: 0, pending: 0 };
185
+ const intents = await this.associations.findRecoverable(new Date(now.getTime() - this.options.paymentRecoveryDelaySecs * 1000));
186
+ if (intents.length === 0)
187
+ return counts;
188
+ const { storeId } = await this.store();
189
+ for (const intent of intents) {
190
+ const result = await this.replay(intent, storeId, now);
191
+ counts[result === "failed" || result === "pending" ? result : "bound"]++;
192
+ }
193
+ return counts;
194
+ }
195
+ async replay(intent, storeId, at) {
196
+ if (intent.state !== "creating")
197
+ return "failed";
198
+ if (intent.storeId !== storeId) {
199
+ // Never replay into another Store: that would create a new Payment there.
200
+ await this.associations.markFailed(intent.id, "store_changed");
201
+ return "failed";
202
+ }
203
+ await this.associations.recordAttempt(intent.id, at);
204
+ return this.submit(intent);
205
+ }
206
+ /**
207
+ * Sends the intent's stored request. 2xx binds, a definitive rejection fails the intent, and any
208
+ * other outcome leaves it `creating` with its key for a later replay.
209
+ */
210
+ async submit(intent) {
211
+ let paymentId;
212
+ try {
213
+ paymentId = await this.api.createPayment(intent.requestBody, intent.idempotencyKey);
214
+ }
215
+ catch (error) {
216
+ if (!(error instanceof public_api_1.TlyApiError) || !error.rejected)
217
+ return "pending";
218
+ if (error.httpStatus === 409)
219
+ core_1.Logger.error(`Payment intent ${intent.id} conflicts with its Idempotency-Key`, LOG_CONTEXT);
220
+ await this.associations.markFailed(intent.id, `rejected_${error.httpStatus}`);
221
+ return "failed";
222
+ }
223
+ const bound = await this.associations.bindPayment(intent.id, paymentId, (0, hosted_checkout_1.hostedCheckoutUrl)(this.options.widgetOrigin, paymentId));
224
+ if (bound.paymentId !== paymentId) {
225
+ core_1.Logger.error(`Payment intent ${intent.id} is bound to another Payment than ${paymentId}`, LOG_CONTEXT);
226
+ throw new TypeError("Vendure Payment association conflicts");
227
+ }
228
+ return bound;
229
+ }
230
+ }
231
+ exports.TlyPayCreationService = TlyPayCreationService;
232
+ /** Whether a stored body charges this exact source amount. */
233
+ function sameSource(requestBody, currency, raw) {
234
+ try {
235
+ const body = JSON.parse(requestBody);
236
+ const source = (0, contracts_1.isRecord)(body) ? body.source_amount : null;
237
+ return (0, contracts_1.isRecord)(source) && source.kind === "fiat" && source.currency === currency && source.amount_raw === raw;
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ }
@@ -0,0 +1,13 @@
1
+ import { PaymentMethodEligibilityChecker, PaymentMethodHandler } from "@vendure/core";
2
+ /**
3
+ * Settles only the Vendure Payment the plugin itself adds after `GET /v1/payments/{id}` reported this
4
+ * Order's Payment as paid: same Order, Channel and amount. Shop API `addPaymentToOrder` is refused;
5
+ * storefronts start TLY Pay with the `createTlyPayPayment` mutation.
6
+ */
7
+ export declare const tlyPayPaymentHandler: PaymentMethodHandler<{}>;
8
+ /**
9
+ * Makes the payment method eligible only while the saved connection is ready, the Store has a
10
+ * verified wallet (`payments_ready`) and the Order uses the Store currency. Vendure checks it again
11
+ * when the plugin settles a verified paid Payment, which stays eligible after such a change.
12
+ */
13
+ export declare const tlyPayEligibilityChecker: PaymentMethodEligibilityChecker<{}>;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tlyPayEligibilityChecker = exports.tlyPayPaymentHandler = void 0;
4
+ const core_1 = require("@vendure/core");
5
+ const service_1 = require("./service");
6
+ let service;
7
+ /**
8
+ * Settles only the Vendure Payment the plugin itself adds after `GET /v1/payments/{id}` reported this
9
+ * Order's Payment as paid: same Order, Channel and amount. Shop API `addPaymentToOrder` is refused;
10
+ * storefronts start TLY Pay with the `createTlyPayPayment` mutation.
11
+ */
12
+ exports.tlyPayPaymentHandler = new core_1.PaymentMethodHandler({
13
+ code: service_1.HANDLER_CODE,
14
+ description: [{ languageCode: core_1.LanguageCode.en, value: "TLY Pay crypto payment" }],
15
+ args: {},
16
+ init(injector) {
17
+ service = injector.get(service_1.TlyPayService);
18
+ },
19
+ createPayment: async (ctx, order, amount, _args, metadata) => {
20
+ if (ctx.apiType !== "admin" || service === undefined) {
21
+ throw new Error("Start TLY Pay with the createTlyPayPayment mutation");
22
+ }
23
+ const paymentId = await service.verifySettlement(ctx, order, amount, metadata.paymentId);
24
+ if (paymentId === null) {
25
+ return { amount, state: "Declined", errorMessage: "TLY Pay has not confirmed this payment" };
26
+ }
27
+ return { amount, state: "Settled", transactionId: paymentId, metadata: { public: { paymentId } } };
28
+ },
29
+ settlePayment: async () => ({ success: true }),
30
+ });
31
+ /**
32
+ * Makes the payment method eligible only while the saved connection is ready, the Store has a
33
+ * verified wallet (`payments_ready`) and the Order uses the Store currency. Vendure checks it again
34
+ * when the plugin settles a verified paid Payment, which stays eligible after such a change.
35
+ */
36
+ exports.tlyPayEligibilityChecker = new core_1.PaymentMethodEligibilityChecker({
37
+ code: service_1.CHECKER_CODE,
38
+ description: [{ languageCode: core_1.LanguageCode.en, value: "TLY Pay connection and wallet are ready" }],
39
+ args: {},
40
+ init(injector) {
41
+ service = injector.get(service_1.TlyPayService);
42
+ },
43
+ check: async (ctx, order) => service !== undefined
44
+ && (await service.eligible(order) || await service.settlable(ctx, order)),
45
+ });
@@ -0,0 +1,3 @@
1
+ /** Builds the current Hosted Checkout v1 destination without placing the ID in query/path. */
2
+ export declare function hostedCheckoutUrl(hostedOrigin: string, paymentId: string): string;
3
+ export declare function isHostedCheckoutUrl(value: string, hostedOrigin: string, paymentId: string): boolean;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hostedCheckoutUrl = hostedCheckoutUrl;
4
+ exports.isHostedCheckoutUrl = isHostedCheckoutUrl;
5
+ const contracts_1 = require("./contracts");
6
+ /** Builds the current Hosted Checkout v1 destination without placing the ID in query/path. */
7
+ function hostedCheckoutUrl(hostedOrigin, paymentId) {
8
+ const origin = (0, contracts_1.requireHttpsOrigin)(hostedOrigin, "Hosted Origin");
9
+ const id = (0, contracts_1.requirePaymentId)(paymentId);
10
+ return `${origin}/#payment_id=${encodeURIComponent(id)}`;
11
+ }
12
+ function isHostedCheckoutUrl(value, hostedOrigin, paymentId) {
13
+ if (typeof value !== "string")
14
+ return false;
15
+ try {
16
+ const parsed = new URL(value);
17
+ return parsed.origin === (0, contracts_1.requireHttpsOrigin)(hostedOrigin, "Hosted Origin")
18
+ && parsed.pathname === "/" && parsed.search === ""
19
+ && parsed.hash === `#payment_id=${encodeURIComponent((0, contracts_1.requirePaymentId)(paymentId))}`
20
+ && contracts_1.PAYMENT_ID.test(decodeURIComponent(parsed.hash.slice("#payment_id=".length)));
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
@@ -0,0 +1,11 @@
1
+ export { TlyPayPlugin, connectionCheckTask, recoveryTask } from "./plugin";
2
+ export { TlyPayService, HANDLER_CODE, CHECKER_CODE } from "./service";
3
+ export type { CheckoutIcon, CheckoutIconOption, CheckoutPresentation, PaymentSession, TlyPayPluginOptions } from "./service";
4
+ export { tlyPayEligibilityChecker, tlyPayPaymentHandler } from "./handler";
5
+ export { TlyPayCheckoutIconSettings, TlyPayCheckoutSettings, TlyPayClientRefService, TlyPayCoinNamesSettings, CLIENT_REF_KEY, CHECKOUT_COIN_NAMES_KEY, CHECKOUT_ICONS_KEY, CHECKOUT_MODE_KEY } from "./client-ref";
6
+ export { CALLBACK_PATH, WEBHOOK_PATH, connectionUrls } from "./connection";
7
+ export type { ConnectionStatus } from "./connection";
8
+ export { TlyPayEvent, TlyPayPaymentIntent } from "./persistence";
9
+ export { TlyPayRecord } from "./records";
10
+ export type { ReleaseConfig } from "./release-config";
11
+ export type { PaymentAsset, PaymentView, SourceAmount, TlyStatus } from "./contracts";
package/dist/index.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TlyPayRecord = exports.TlyPayPaymentIntent = exports.TlyPayEvent = exports.connectionUrls = exports.WEBHOOK_PATH = exports.CALLBACK_PATH = exports.CHECKOUT_MODE_KEY = exports.CHECKOUT_ICONS_KEY = exports.CHECKOUT_COIN_NAMES_KEY = exports.CLIENT_REF_KEY = exports.TlyPayCoinNamesSettings = exports.TlyPayClientRefService = exports.TlyPayCheckoutSettings = exports.TlyPayCheckoutIconSettings = exports.tlyPayPaymentHandler = exports.tlyPayEligibilityChecker = exports.CHECKER_CODE = exports.HANDLER_CODE = exports.TlyPayService = exports.recoveryTask = exports.connectionCheckTask = exports.TlyPayPlugin = void 0;
4
+ var plugin_1 = require("./plugin");
5
+ Object.defineProperty(exports, "TlyPayPlugin", { enumerable: true, get: function () { return plugin_1.TlyPayPlugin; } });
6
+ Object.defineProperty(exports, "connectionCheckTask", { enumerable: true, get: function () { return plugin_1.connectionCheckTask; } });
7
+ Object.defineProperty(exports, "recoveryTask", { enumerable: true, get: function () { return plugin_1.recoveryTask; } });
8
+ var service_1 = require("./service");
9
+ Object.defineProperty(exports, "TlyPayService", { enumerable: true, get: function () { return service_1.TlyPayService; } });
10
+ Object.defineProperty(exports, "HANDLER_CODE", { enumerable: true, get: function () { return service_1.HANDLER_CODE; } });
11
+ Object.defineProperty(exports, "CHECKER_CODE", { enumerable: true, get: function () { return service_1.CHECKER_CODE; } });
12
+ var handler_1 = require("./handler");
13
+ Object.defineProperty(exports, "tlyPayEligibilityChecker", { enumerable: true, get: function () { return handler_1.tlyPayEligibilityChecker; } });
14
+ Object.defineProperty(exports, "tlyPayPaymentHandler", { enumerable: true, get: function () { return handler_1.tlyPayPaymentHandler; } });
15
+ var client_ref_1 = require("./client-ref");
16
+ Object.defineProperty(exports, "TlyPayCheckoutIconSettings", { enumerable: true, get: function () { return client_ref_1.TlyPayCheckoutIconSettings; } });
17
+ Object.defineProperty(exports, "TlyPayCheckoutSettings", { enumerable: true, get: function () { return client_ref_1.TlyPayCheckoutSettings; } });
18
+ Object.defineProperty(exports, "TlyPayClientRefService", { enumerable: true, get: function () { return client_ref_1.TlyPayClientRefService; } });
19
+ Object.defineProperty(exports, "TlyPayCoinNamesSettings", { enumerable: true, get: function () { return client_ref_1.TlyPayCoinNamesSettings; } });
20
+ Object.defineProperty(exports, "CLIENT_REF_KEY", { enumerable: true, get: function () { return client_ref_1.CLIENT_REF_KEY; } });
21
+ Object.defineProperty(exports, "CHECKOUT_COIN_NAMES_KEY", { enumerable: true, get: function () { return client_ref_1.CHECKOUT_COIN_NAMES_KEY; } });
22
+ Object.defineProperty(exports, "CHECKOUT_ICONS_KEY", { enumerable: true, get: function () { return client_ref_1.CHECKOUT_ICONS_KEY; } });
23
+ Object.defineProperty(exports, "CHECKOUT_MODE_KEY", { enumerable: true, get: function () { return client_ref_1.CHECKOUT_MODE_KEY; } });
24
+ var connection_1 = require("./connection");
25
+ Object.defineProperty(exports, "CALLBACK_PATH", { enumerable: true, get: function () { return connection_1.CALLBACK_PATH; } });
26
+ Object.defineProperty(exports, "WEBHOOK_PATH", { enumerable: true, get: function () { return connection_1.WEBHOOK_PATH; } });
27
+ Object.defineProperty(exports, "connectionUrls", { enumerable: true, get: function () { return connection_1.connectionUrls; } });
28
+ var persistence_1 = require("./persistence");
29
+ Object.defineProperty(exports, "TlyPayEvent", { enumerable: true, get: function () { return persistence_1.TlyPayEvent; } });
30
+ Object.defineProperty(exports, "TlyPayPaymentIntent", { enumerable: true, get: function () { return persistence_1.TlyPayPaymentIntent; } });
31
+ var records_1 = require("./records");
32
+ Object.defineProperty(exports, "TlyPayRecord", { enumerable: true, get: function () { return records_1.TlyPayRecord; } });
@@ -0,0 +1,38 @@
1
+ import { AssociationStore, PaymentAssociation, TlyPayCreationService } from "./creation-service";
2
+ import { SignedPaymentEvent, SignedPaymentFields } from "./signed-webhook";
3
+ /**
4
+ * What the host Webhook route does with a verified event. Every active Webhook of the TLY Store
5
+ * receives every Payment event, so events created by other installations arrive here too.
6
+ * - `process`: store the event, hand it to the worker and answer 204 once it is stored, also when its
7
+ * Event ID is already stored. Answer 503 only while storage temporarily fails. `payment` carries the
8
+ * validated Payment fields of the event.
9
+ * - `reject`: answer 400 without storing and log it; the signed event of a known local Payment has
10
+ * invalid Payment fields, so retrying cannot fix it.
11
+ * - `retry`: answer 503 without storing; replaying this installation's creation intent failed
12
+ * transiently, so TLY Pay retries the event.
13
+ * - `ignore`: answer 204 without storing. `no_intent` carries this installation's marker but no
14
+ * local intent creates that Payment and should be logged.
15
+ */
16
+ export type OwnershipDecision = {
17
+ action: "process";
18
+ association: PaymentAssociation;
19
+ payment: SignedPaymentFields;
20
+ } | {
21
+ action: "reject";
22
+ httpStatus: 400;
23
+ reason: "invalid_payment";
24
+ } | {
25
+ action: "retry";
26
+ httpStatus: 503;
27
+ } | {
28
+ action: "ignore";
29
+ httpStatus: 204;
30
+ reason: "foreign" | "unknown_payment" | "no_intent";
31
+ };
32
+ /**
33
+ * An unknown Payment carrying this installation's `client_ref` may have been created by a request
34
+ * whose response was lost; replaying the matching `creating` intents binds it before processing.
35
+ * The Payment fields are validated only for a known Payment, so another installation's event is
36
+ * ignored whatever its source.
37
+ */
38
+ export declare function decideOwnership(event: SignedPaymentEvent, clientRef: string, associations: Pick<AssociationStore, "findByPaymentId">, creation: Pick<TlyPayCreationService, "recoverForEvent">): Promise<OwnershipDecision>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decideOwnership = decideOwnership;
4
+ const signed_webhook_1 = require("./signed-webhook");
5
+ /**
6
+ * An unknown Payment carrying this installation's `client_ref` may have been created by a request
7
+ * whose response was lost; replaying the matching `creating` intents binds it before processing.
8
+ * The Payment fields are validated only for a known Payment, so another installation's event is
9
+ * ignored whatever its source.
10
+ */
11
+ async function decideOwnership(event, clientRef, associations, creation) {
12
+ if (event.clientRef !== null && event.clientRef !== clientRef) {
13
+ return { action: "ignore", httpStatus: 204, reason: "foreign" };
14
+ }
15
+ const association = await associations.findByPaymentId(event.paymentId);
16
+ if (association !== null)
17
+ return processKnown(event, association);
18
+ if (event.clientRef === null)
19
+ return { action: "ignore", httpStatus: 204, reason: "unknown_payment" };
20
+ if (event.orderRef === null)
21
+ return { action: "ignore", httpStatus: 204, reason: "no_intent" };
22
+ const recovery = await creation.recoverForEvent(event.orderRef, event.paymentId);
23
+ if (recovery.outcome === "bound")
24
+ return processKnown(event, recovery.association);
25
+ if (recovery.outcome === "pending")
26
+ return { action: "retry", httpStatus: 503 };
27
+ return { action: "ignore", httpStatus: 204, reason: "no_intent" };
28
+ }
29
+ function processKnown(event, association) {
30
+ try {
31
+ return { action: "process", association, payment: (0, signed_webhook_1.validateEventPayment)(event) };
32
+ }
33
+ catch (error) {
34
+ if (error instanceof signed_webhook_1.InvalidEventPayment)
35
+ return { action: "reject", httpStatus: 400, reason: "invalid_payment" };
36
+ throw error;
37
+ }
38
+ }
@@ -0,0 +1,45 @@
1
+ import { Connection } from "./connection";
2
+ import { TlyStatus } from "./contracts";
3
+ import { AssociationStore, PaymentAssociation } from "./creation-service";
4
+ import { PublicApiClient } from "./public-api";
5
+ /** Vendure side of a synchronized Payment, implemented by the plugin service on the Order APIs. */
6
+ export interface OrderPort {
7
+ /**
8
+ * Adds the Settled Vendure Payment for a paid Payment once: `settled`, `already_settled`, or a stable
9
+ * code why the Order cannot take it (for example `amount_mismatch`, `order_missing`).
10
+ */
11
+ settle(intent: PaymentAssociation): Promise<string>;
12
+ /** Adds an Order history note for a newly applied status that needs attention. */
13
+ note(intent: PaymentAssociation, status: TlyStatus): Promise<void>;
14
+ }
15
+ export interface SyncStore extends Pick<AssociationStore, "findByPaymentId" | "recordAuthority"> {
16
+ /** Claims settlement until `until`: `claimed`, `busy` (another worker holds it) or `settled` (done before). */
17
+ claimSettlement(id: string, now: Date, until: Date): Promise<"claimed" | "busy" | "settled">;
18
+ finishSettlement(id: string, settled: boolean, err: string | null): Promise<void>;
19
+ }
20
+ export interface SyncInbox {
21
+ finish(paymentId: string, version: number, outcome: string): Promise<void>;
22
+ reject(paymentId: string, outcome: string): Promise<void>;
23
+ }
24
+ /**
25
+ * Applies the authoritative status of one local Payment: reads `GET /v1/payments/{id}` with the saved
26
+ * connection, checks it against the stored intent (Order code, `client_ref`, exact source amount),
27
+ * records it only when its version is newer and settles the Vendure Order once for `paid` and
28
+ * `overpaid`. `partially_paid` and `review_required` stay out of fulfillment with an Order note.
29
+ * A transient failure throws so the job or the scheduled sweep retries; a definitive mismatch marks
30
+ * the stored Events with its code.
31
+ */
32
+ export declare class PaymentSync {
33
+ private readonly store;
34
+ private readonly inbox;
35
+ private readonly orders;
36
+ private readonly connection;
37
+ private readonly api;
38
+ private readonly clientRef;
39
+ private readonly claimSecs;
40
+ constructor(store: SyncStore, inbox: SyncInbox, orders: OrderPort, connection: () => Promise<Connection | null>, api: (apiKey: string) => Promise<PublicApiClient>, clientRef: () => Promise<string>, claimSecs: number);
41
+ sync(paymentId: string, now?: Date): Promise<string>;
42
+ private settle;
43
+ private mismatch;
44
+ private reject;
45
+ }