@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
package/dist/plugin.js ADDED
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var TlyPayPlugin_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.TlyPayPlugin = exports.recoveryTask = exports.connectionCheckTask = void 0;
11
+ const core_1 = require("@vendure/core");
12
+ const api_1 = require("./api");
13
+ const client_ref_1 = require("./client-ref");
14
+ const connection_1 = require("./connection");
15
+ const handler_1 = require("./handler");
16
+ const persistence_1 = require("./persistence");
17
+ const records_1 = require("./records");
18
+ const secret_box_1 = require("./secret-box");
19
+ const service_1 = require("./service");
20
+ /** Hourly recheck of the saved connection, like the WooCommerce plugin's hourly check. */
21
+ exports.connectionCheckTask = new core_1.ScheduledTask({
22
+ id: "tly-pay-connection-check",
23
+ description: "Rechecks the TLY Pay connection, Store readiness and Webhook Secrets",
24
+ schedule: (cron) => cron.everyHour(),
25
+ preventOverlap: true,
26
+ execute: async ({ injector }) => injector.get(service_1.TlyPayService).refreshConnection(),
27
+ });
28
+ /**
29
+ * Runs the early connection check after a transient failure, replays due Payment creation intents and
30
+ * dispatches stored Events that are still unprocessed.
31
+ */
32
+ exports.recoveryTask = new core_1.ScheduledTask({
33
+ id: "tly-pay-recovery",
34
+ description: "Recovers TLY Pay Payment creation and Webhook processing",
35
+ schedule: (cron) => cron.everyMinute(),
36
+ preventOverlap: true,
37
+ execute: async ({ injector }) => injector.get(service_1.TlyPayService).recover(),
38
+ });
39
+ /**
40
+ * TLY Pay crypto payments for Vendure 3.8.
41
+ *
42
+ * Registers the "TLY Pay" payment method handler and its readiness eligibility checker, the Shop API
43
+ * `tlyPayCheckout` query and `createTlyPayPayment` mutation, the Admin API used by the Dashboard
44
+ * extension, the REST routes `/tly-pay/webhook` and `/tly-pay/connect/return`, the encrypted connection
45
+ * storage, the Payment and Event tables, the sync job queue and the scheduled connection check and
46
+ * recovery tasks.
47
+ */
48
+ let TlyPayPlugin = class TlyPayPlugin {
49
+ static { TlyPayPlugin_1 = this; }
50
+ static options;
51
+ /**
52
+ * Configures the plugin with the host's site-private values. `publicUrl` is the public HTTPS URL of
53
+ * this Vendure server's REST routes; `secretKey` encrypts the saved connection at rest.
54
+ */
55
+ static init(options) {
56
+ if (options === null || typeof options !== "object" || typeof options.publicUrl !== "string"
57
+ || !URL.canParse(options.publicUrl)) {
58
+ throw new TypeError("TlyPayPlugin.init() requires publicUrl, the public URL of this Vendure server");
59
+ }
60
+ if (typeof options.secretKey !== "string" || options.secretKey.length < secret_box_1.MIN_SECRET_KEY_LENGTH) {
61
+ throw new TypeError(`TlyPayPlugin.init() requires a secretKey of at least ${secret_box_1.MIN_SECRET_KEY_LENGTH} characters`);
62
+ }
63
+ this.options = { publicUrl: options.publicUrl, secretKey: options.secretKey };
64
+ return TlyPayPlugin_1;
65
+ }
66
+ };
67
+ exports.TlyPayPlugin = TlyPayPlugin;
68
+ exports.TlyPayPlugin = TlyPayPlugin = TlyPayPlugin_1 = __decorate([
69
+ (0, core_1.VendurePlugin)({
70
+ imports: [core_1.PluginCommonModule],
71
+ providers: [
72
+ { provide: service_1.TLY_PAY_PLUGIN_OPTIONS, useFactory: () => TlyPayPlugin.options },
73
+ {
74
+ provide: client_ref_1.TlyPayClientRefService,
75
+ useFactory: (connection) => new client_ref_1.TlyPayClientRefService(connection),
76
+ inject: [core_1.TransactionalConnection],
77
+ },
78
+ service_1.TlyPayService,
79
+ ],
80
+ exports: [client_ref_1.TlyPayClientRefService, service_1.TlyPayService],
81
+ controllers: [api_1.TlyPayController],
82
+ entities: [records_1.TlyPayRecord, persistence_1.TlyPayPaymentIntent, persistence_1.TlyPayEvent],
83
+ shopApiExtensions: { schema: api_1.shopApiExtensions, resolvers: [api_1.TlyPayShopResolver] },
84
+ adminApiExtensions: { schema: api_1.adminApiExtensions, resolvers: [api_1.TlyPayAdminResolver] },
85
+ dashboard: "../dashboard/index.tsx",
86
+ configuration: (config) => {
87
+ const fields = config.settingsStoreFields?.[client_ref_1.CLIENT_REF_NAMESPACE] ?? [];
88
+ config.settingsStoreFields = {
89
+ ...config.settingsStoreFields,
90
+ [client_ref_1.CLIENT_REF_NAMESPACE]: [
91
+ ...fields.filter((field) => ![client_ref_1.CLIENT_REF_FIELD, client_ref_1.CHECKOUT_MODE_FIELD, client_ref_1.CHECKOUT_ICONS_FIELD,
92
+ client_ref_1.CHECKOUT_COIN_NAMES_FIELD, client_ref_1.SITE_MODE_FIELD].includes(field.name)),
93
+ { name: client_ref_1.CLIENT_REF_FIELD, readonly: true, requiresPermission: core_1.Permission.SuperAdmin },
94
+ { name: client_ref_1.CHECKOUT_MODE_FIELD, readonly: true, requiresPermission: core_1.Permission.ReadSettings },
95
+ { name: client_ref_1.CHECKOUT_ICONS_FIELD, readonly: true, requiresPermission: core_1.Permission.ReadSettings },
96
+ { name: client_ref_1.CHECKOUT_COIN_NAMES_FIELD, readonly: true, requiresPermission: core_1.Permission.ReadSettings },
97
+ { name: client_ref_1.SITE_MODE_FIELD, readonly: true, requiresPermission: core_1.Permission.ReadSettings },
98
+ ],
99
+ };
100
+ const payment = config.paymentOptions;
101
+ payment.paymentMethodHandlers = [...payment.paymentMethodHandlers.filter((h) => h.code !== handler_1.tlyPayPaymentHandler.code),
102
+ handler_1.tlyPayPaymentHandler];
103
+ payment.paymentMethodEligibilityCheckers = [...(payment.paymentMethodEligibilityCheckers ?? [])
104
+ .filter((c) => c.code !== handler_1.tlyPayEligibilityChecker.code), handler_1.tlyPayEligibilityChecker];
105
+ config.apiOptions.middleware = [...(config.apiOptions.middleware ?? []),
106
+ { route: connection_1.WEBHOOK_PATH, handler: api_1.rawWebhookBody, beforeListen: true }];
107
+ config.schedulerOptions.tasks = [...(config.schedulerOptions.tasks ?? []).filter((task) => task.id !== exports.connectionCheckTask.id && task.id !== exports.recoveryTask.id), exports.connectionCheckTask, exports.recoveryTask];
108
+ return config;
109
+ },
110
+ compatibility: ">=3.8.0 <3.9.0",
111
+ })
112
+ ], TlyPayPlugin);
@@ -0,0 +1,56 @@
1
+ import { PaymentView, StoreContext } from "./contracts";
2
+ import { ReleaseConfig } from "./release-config";
3
+ /** Platform id of this plugin in the platform connection registry. */
4
+ export declare const PLATFORM = "vendure";
5
+ /**
6
+ * A failed Public API request with a stable, non-sensitive code. `retryable` marks transient
7
+ * failures (network, timeout, 408, 425, 429, 5xx) that must not withdraw checkout; `retryAfterSecs`
8
+ * is the server's announced wait, when any.
9
+ */
10
+ export declare class TlyApiError extends Error {
11
+ readonly code: string;
12
+ readonly retryable: boolean;
13
+ readonly httpStatus: number | null;
14
+ readonly retryAfterSecs: number | null;
15
+ constructor(code: string, retryable: boolean, httpStatus?: number | null, retryAfterSecs?: number | null);
16
+ /** TLY Pay definitively rejected the request; replaying the same request cannot succeed. */
17
+ get rejected(): boolean;
18
+ }
19
+ /** Credentials of `POST /v1/plugins/vendure/exchange`. */
20
+ export type ExchangedCredentials = {
21
+ apiKey: string;
22
+ endpointId: string;
23
+ webhookSecret: string;
24
+ pendingWebhookSecret: string;
25
+ };
26
+ export type WebhookSecrets = {
27
+ webhookSecret: string;
28
+ pendingWebhookSecret: string;
29
+ };
30
+ type Transport = (input: string | URL, init?: RequestInit) => Promise<Response>;
31
+ /** Reads `Retry-After` as delay seconds or an HTTP-date; unparseable values are ignored. */
32
+ export declare function retryAfterSecs(header: string | null, nowMs?: number): number | null;
33
+ export declare class PublicApiClient {
34
+ private readonly release;
35
+ private readonly apiKey;
36
+ private readonly transport;
37
+ constructor(release: Pick<ReleaseConfig, "apiOrigin" | "apiTimeoutSecs" | "apiMaxResponseBytes">, apiKey: string, transport?: Transport);
38
+ exchangeConnection(code: string, codeVerifier: string, redirectUri: string, existingApiKey: string): Promise<ExchangedCredentials>;
39
+ /** Reads the Store bound to the API Key; status, source and currency checks belong to the caller. */
40
+ getStore(): Promise<StoreContext>;
41
+ /** Verifies that an Endpoint and one of its Secrets belong to the API Key's Store. */
42
+ verifyEndpointSecret(endpointId: string, secret: string): Promise<{
43
+ secretKind: string;
44
+ status: string;
45
+ }>;
46
+ /** Synchronizes the signing Secrets, or acknowledges that they are saved locally. */
47
+ synchronizeConnection(endpointId: string, webhookUrl: string, secret: string, acknowledge: boolean): Promise<WebhookSecrets>;
48
+ /** Sends the exact stored create body; a replay with the same key and body returns the same Payment. */
49
+ createPayment(requestBody: string, key: string): Promise<string>;
50
+ getPayment(paymentId: string): Promise<PaymentView>;
51
+ cancelPayment(paymentId: string): Promise<PaymentView>;
52
+ private request;
53
+ /** Reads at most the packaged response limit and decodes strict UTF-8 JSON. */
54
+ private readJson;
55
+ }
56
+ export {};
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PublicApiClient = exports.TlyApiError = exports.PLATFORM = void 0;
4
+ exports.retryAfterSecs = retryAfterSecs;
5
+ const contracts_1 = require("./contracts");
6
+ /** Platform id of this plugin in the platform connection registry. */
7
+ exports.PLATFORM = "vendure";
8
+ /** 4xx responses that do not settle a request: authorization may return, the rest are transient. */
9
+ const AMBIGUOUS_STATUSES = new Set([401, 403, 408, 425, 429]);
10
+ const RETRYABLE_STATUSES = new Set([408, 425, 429]);
11
+ const ERR_CODE = /^[a-z0-9_]{1,64}$/;
12
+ /**
13
+ * A failed Public API request with a stable, non-sensitive code. `retryable` marks transient
14
+ * failures (network, timeout, 408, 425, 429, 5xx) that must not withdraw checkout; `retryAfterSecs`
15
+ * is the server's announced wait, when any.
16
+ */
17
+ class TlyApiError extends Error {
18
+ code;
19
+ retryable;
20
+ httpStatus;
21
+ retryAfterSecs;
22
+ constructor(code, retryable, httpStatus = null, retryAfterSecs = null) {
23
+ super(`TLY Pay request failed: ${code}`);
24
+ this.code = code;
25
+ this.retryable = retryable;
26
+ this.httpStatus = httpStatus;
27
+ this.retryAfterSecs = retryAfterSecs;
28
+ }
29
+ /** TLY Pay definitively rejected the request; replaying the same request cannot succeed. */
30
+ get rejected() {
31
+ return this.httpStatus !== null && this.httpStatus >= 400 && this.httpStatus < 500
32
+ && !AMBIGUOUS_STATUSES.has(this.httpStatus);
33
+ }
34
+ }
35
+ exports.TlyApiError = TlyApiError;
36
+ /** Reads `Retry-After` as delay seconds or an HTTP-date; unparseable values are ignored. */
37
+ function retryAfterSecs(header, nowMs = Date.now()) {
38
+ if (header === null || header.trim() === "")
39
+ return null;
40
+ const value = header.trim();
41
+ if (/^[0-9]{1,9}$/.test(value))
42
+ return Number(value);
43
+ const at = Date.parse(value);
44
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - nowMs) / 1000));
45
+ }
46
+ class PublicApiClient {
47
+ release;
48
+ apiKey;
49
+ transport;
50
+ constructor(release, apiKey, transport = fetch) {
51
+ this.release = release;
52
+ this.apiKey = apiKey;
53
+ this.transport = transport;
54
+ }
55
+ async exchangeConnection(code, codeVerifier, redirectUri, existingApiKey) {
56
+ const value = await this.request("POST", `/v1/plugins/${exports.PLATFORM}/exchange`, JSON.stringify({
57
+ code, code_verifier: codeVerifier, redirect_uri: redirectUri, existing_api_key: existingApiKey,
58
+ }), undefined, false);
59
+ if (!(0, contracts_1.hasFields)(value, ["api_key", "webhook_endpoint_id", "webhook_secret", "pending_webhook_secret"])
60
+ || typeof value.api_key !== "string" || typeof value.webhook_endpoint_id !== "string"
61
+ || typeof value.webhook_secret !== "string" || typeof value.pending_webhook_secret !== "string") {
62
+ throw new TlyApiError("invalid_response", false);
63
+ }
64
+ return { apiKey: value.api_key, endpointId: value.webhook_endpoint_id, webhookSecret: value.webhook_secret,
65
+ pendingWebhookSecret: value.pending_webhook_secret };
66
+ }
67
+ /** Reads the Store bound to the API Key; status, source and currency checks belong to the caller. */
68
+ async getStore() {
69
+ const value = await this.request("GET", "/v1/store");
70
+ const assets = (0, contracts_1.isRecord)(value) ? (0, contracts_1.parsePaymentAssets)(value.payment_assets) : null;
71
+ if (!(0, contracts_1.hasFields)(value, ["store_id", "display_name", "primary_source", "merchant_site_registrable_domain",
72
+ "status", "payments_ready", "payment_assets"])
73
+ || typeof value.store_id !== "string" || !contracts_1.STORE_ID.test(value.store_id)
74
+ || typeof value.display_name !== "string" || typeof value.status !== "string"
75
+ || typeof value.payments_ready !== "boolean" || assets === null
76
+ || value.merchant_site_registrable_domain !== null && typeof value.merchant_site_registrable_domain !== "string"
77
+ || !(0, contracts_1.hasFields)(value.primary_source, ["kind", "ref", "decimals"])
78
+ || typeof value.primary_source.kind !== "string" || typeof value.primary_source.ref !== "string"
79
+ || !Number.isInteger(value.primary_source.decimals) || value.primary_source.decimals < 0
80
+ || value.primary_source.decimals > 18) {
81
+ throw new TlyApiError("invalid_store_context", false);
82
+ }
83
+ return {
84
+ storeId: value.store_id,
85
+ displayName: value.display_name,
86
+ status: value.status,
87
+ sourceKind: value.primary_source.kind,
88
+ sourceCurrency: value.primary_source.ref.toUpperCase(),
89
+ sourceDecimals: value.primary_source.decimals,
90
+ merchantDomain: typeof value.merchant_site_registrable_domain === "string"
91
+ ? value.merchant_site_registrable_domain.toLowerCase().replace(/\.$/, "") : "",
92
+ paymentsReady: value.payments_ready,
93
+ paymentAssets: assets,
94
+ };
95
+ }
96
+ /** Verifies that an Endpoint and one of its Secrets belong to the API Key's Store. */
97
+ async verifyEndpointSecret(endpointId, secret) {
98
+ if (!contracts_1.WEBHOOK_ENDPOINT_ID.test(endpointId))
99
+ throw new TlyApiError("invalid_webhook_endpoint_id", false);
100
+ const value = await this.request("POST", `/v1/webhook-endpoints/${endpointId}/verify`, JSON.stringify({ secret }));
101
+ if (!(0, contracts_1.hasFields)(value, ["resource_id", "secret_kind", "status"]) || value.resource_id !== endpointId
102
+ || typeof value.secret_kind !== "string" || typeof value.status !== "string") {
103
+ throw new TlyApiError("invalid_webhook_binding", false);
104
+ }
105
+ return { secretKind: value.secret_kind, status: value.status };
106
+ }
107
+ /** Synchronizes the signing Secrets, or acknowledges that they are saved locally. */
108
+ async synchronizeConnection(endpointId, webhookUrl, secret, acknowledge) {
109
+ const value = await this.request("POST", `/v1/plugins/${exports.PLATFORM}/connection`, JSON.stringify({
110
+ webhook_endpoint_id: endpointId, webhook_url: webhookUrl, secret, acknowledge,
111
+ }));
112
+ if (!(0, contracts_1.hasFields)(value, ["webhook_secret", "pending_webhook_secret"]) || typeof value.webhook_secret !== "string"
113
+ || value.webhook_secret === "" || typeof value.pending_webhook_secret !== "string") {
114
+ throw new TlyApiError("invalid_webhook_response", false);
115
+ }
116
+ return { webhookSecret: value.webhook_secret, pendingWebhookSecret: value.pending_webhook_secret };
117
+ }
118
+ /** Sends the exact stored create body; a replay with the same key and body returns the same Payment. */
119
+ async createPayment(requestBody, key) {
120
+ if (typeof requestBody !== "string" || requestBody === "" || !/^[\x21-\x7e]{1,255}$/.test(key)) {
121
+ throw new TypeError("Invalid Vendure Payment creation request");
122
+ }
123
+ const value = await this.request("POST", "/v1/payments", requestBody, key);
124
+ if (!(0, contracts_1.hasFields)(value, ["payment_id"]) || typeof value.payment_id !== "string") {
125
+ throw new TypeError("Invalid Payment creation response");
126
+ }
127
+ return (0, contracts_1.requirePaymentId)(value.payment_id);
128
+ }
129
+ async getPayment(paymentId) {
130
+ const id = (0, contracts_1.requirePaymentId)(paymentId);
131
+ return (0, contracts_1.validatePaymentView)(await this.request("GET", `/v1/payments/${id}`), id);
132
+ }
133
+ async cancelPayment(paymentId) {
134
+ const id = (0, contracts_1.requirePaymentId)(paymentId);
135
+ const view = (0, contracts_1.validatePaymentView)(await this.request("POST", `/v1/payments/${id}/cancel`), id);
136
+ if (view.status !== "cancelled" && view.status !== "expired") {
137
+ throw new TypeError("Payment cancellation was not confirmed");
138
+ }
139
+ return view;
140
+ }
141
+ async request(method, path, body, idempotencyKey, authenticated = true) {
142
+ if (authenticated && !/^[\x21-\x7e]{1,255}$/.test(this.apiKey))
143
+ throw new TlyApiError("api_key_required", false);
144
+ const controller = new AbortController();
145
+ const timer = setTimeout(() => controller.abort(), this.release.apiTimeoutSecs * 1000);
146
+ try {
147
+ const headers = { Accept: "application/json" };
148
+ if (authenticated)
149
+ headers.Authorization = `Bearer ${this.apiKey}`;
150
+ if (body !== undefined)
151
+ headers["Content-Type"] = "application/json";
152
+ if (idempotencyKey !== undefined)
153
+ headers["Idempotency-Key"] = idempotencyKey;
154
+ let response;
155
+ try {
156
+ response = await this.transport(this.release.apiOrigin + path, {
157
+ method, headers, body, redirect: "manual", signal: controller.signal,
158
+ });
159
+ }
160
+ catch {
161
+ throw new TlyApiError("upstream_unavailable", true);
162
+ }
163
+ const status = response.status;
164
+ const retryable = RETRYABLE_STATUSES.has(status) || status >= 500;
165
+ const retryAfter = retryable ? retryAfterSecs(response.headers.get("retry-after")) : null;
166
+ let value;
167
+ try {
168
+ value = await this.readJson(response);
169
+ }
170
+ catch (error) {
171
+ if (error instanceof TlyApiError)
172
+ throw error;
173
+ throw new TlyApiError("invalid_response", retryable, status, retryAfter);
174
+ }
175
+ if (status < 200 || status >= 300) {
176
+ const code = (0, contracts_1.isRecord)(value) && typeof value.err === "string" && ERR_CODE.test(value.err)
177
+ ? value.err : "request_failed";
178
+ throw new TlyApiError(code, retryable, status, retryAfter);
179
+ }
180
+ return value;
181
+ }
182
+ finally {
183
+ clearTimeout(timer);
184
+ }
185
+ }
186
+ /** Reads at most the packaged response limit and decodes strict UTF-8 JSON. */
187
+ async readJson(response) {
188
+ const limit = this.release.apiMaxResponseBytes;
189
+ const length = response.headers.get("content-length");
190
+ if (response.body === null || length !== null && /^\d+$/.test(length) && Number(length) > limit) {
191
+ throw new TlyApiError("invalid_response", false, response.status);
192
+ }
193
+ const reader = response.body.getReader();
194
+ const chunks = [];
195
+ let size = 0;
196
+ try {
197
+ while (true) {
198
+ let part;
199
+ try {
200
+ part = await reader.read();
201
+ }
202
+ catch {
203
+ throw new TlyApiError("upstream_unavailable", true);
204
+ }
205
+ if (part.done)
206
+ break;
207
+ size += part.value.byteLength;
208
+ if (size > limit) {
209
+ await reader.cancel();
210
+ throw new TlyApiError("invalid_response", false, response.status);
211
+ }
212
+ chunks.push(part.value);
213
+ }
214
+ }
215
+ finally {
216
+ reader.releaseLock();
217
+ }
218
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
219
+ }
220
+ }
221
+ exports.PublicApiClient = PublicApiClient;
@@ -0,0 +1,53 @@
1
+ import { TransactionalConnection } from "@vendure/core";
2
+ import { SecretBox } from "./secret-box";
3
+ /** Names of the sealed records: the active connection and the pending authorization. */
4
+ export type RecordName = "connection" | "pending_connect";
5
+ export type StoredRecord = {
6
+ value: string;
7
+ revision: number;
8
+ };
9
+ /**
10
+ * Raw persistence of sealed records with compare-and-set on `revision`, so a check that ran against
11
+ * an older connection never overwrites a replacement saved meanwhile.
12
+ */
13
+ export interface RecordStore {
14
+ get(name: RecordName): Promise<StoredRecord | null>;
15
+ /** Inserts when `expectedRevision` is null, otherwise updates only that revision; false on conflict. */
16
+ put(name: RecordName, value: string, expectedRevision: number | null): Promise<boolean>;
17
+ delete(name: RecordName): Promise<void>;
18
+ }
19
+ /** One sealed JSON record; the value column holds only AES-256-GCM ciphertext. */
20
+ export declare class TlyPayRecord {
21
+ name: string;
22
+ value: string;
23
+ revision: number;
24
+ updatedAt: Date;
25
+ }
26
+ /** Uses the raw autocommit connection, outside any host request transaction. */
27
+ export declare class TypeOrmRecordStore implements RecordStore {
28
+ private readonly connection;
29
+ constructor(connection: TransactionalConnection);
30
+ private repository;
31
+ get(name: RecordName): Promise<StoredRecord | null>;
32
+ put(name: RecordName, value: string, expectedRevision: number | null): Promise<boolean>;
33
+ delete(name: RecordName): Promise<void>;
34
+ }
35
+ export type Snapshot<T> = {
36
+ data: T;
37
+ revision: number;
38
+ };
39
+ /** JSON records sealed with the SecretBox; reading a record sealed with another key throws. */
40
+ export declare class SealedRecords {
41
+ private readonly store;
42
+ private readonly box;
43
+ constructor(store: RecordStore, box: SecretBox);
44
+ read<T>(name: RecordName): Promise<Snapshot<T> | null>;
45
+ /** Replaces the record read as `expected` (null: not present); false when it changed meanwhile. */
46
+ replace<T>(name: RecordName, expected: Snapshot<T> | null, data: T): Promise<boolean>;
47
+ /** Writes the record whatever it holds now, also over a value sealed with another key. */
48
+ overwrite<T>(name: RecordName, data: T): Promise<void>;
49
+ delete(name: RecordName): Promise<void>;
50
+ }
51
+ export declare class RecordConflict extends Error {
52
+ constructor();
53
+ }
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.RecordConflict = exports.SealedRecords = exports.TypeOrmRecordStore = exports.TlyPayRecord = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ /** One sealed JSON record; the value column holds only AES-256-GCM ciphertext. */
15
+ let TlyPayRecord = class TlyPayRecord {
16
+ name;
17
+ value;
18
+ revision;
19
+ updatedAt;
20
+ };
21
+ exports.TlyPayRecord = TlyPayRecord;
22
+ __decorate([
23
+ (0, typeorm_1.PrimaryColumn)({ type: "varchar", length: 32 }),
24
+ __metadata("design:type", String)
25
+ ], TlyPayRecord.prototype, "name", void 0);
26
+ __decorate([
27
+ (0, typeorm_1.Column)({ type: "text" }),
28
+ __metadata("design:type", String)
29
+ ], TlyPayRecord.prototype, "value", void 0);
30
+ __decorate([
31
+ (0, typeorm_1.Column)({ type: "int" }),
32
+ __metadata("design:type", Number)
33
+ ], TlyPayRecord.prototype, "revision", void 0);
34
+ __decorate([
35
+ (0, typeorm_1.UpdateDateColumn)(),
36
+ __metadata("design:type", Date)
37
+ ], TlyPayRecord.prototype, "updatedAt", void 0);
38
+ exports.TlyPayRecord = TlyPayRecord = __decorate([
39
+ (0, typeorm_1.Entity)("tlypay_vd_record")
40
+ ], TlyPayRecord);
41
+ /** Uses the raw autocommit connection, outside any host request transaction. */
42
+ class TypeOrmRecordStore {
43
+ connection;
44
+ constructor(connection) {
45
+ this.connection = connection;
46
+ }
47
+ repository() {
48
+ return this.connection.rawConnection.getRepository(TlyPayRecord);
49
+ }
50
+ async get(name) {
51
+ const row = await this.repository().findOne({ where: { name } });
52
+ return row === null ? null : { value: row.value, revision: row.revision };
53
+ }
54
+ async put(name, value, expectedRevision) {
55
+ if (expectedRevision === null) {
56
+ try {
57
+ await this.repository().insert({ name, value, revision: 1 });
58
+ return true;
59
+ }
60
+ catch {
61
+ // The primary key rejects a concurrent insert; the caller rereads.
62
+ return false;
63
+ }
64
+ }
65
+ const result = await this.repository().createQueryBuilder().update(TlyPayRecord)
66
+ .set({ value, revision: expectedRevision + 1 })
67
+ .where("name = :name AND revision = :revision", { name, revision: expectedRevision })
68
+ .execute();
69
+ return result.affected === 1;
70
+ }
71
+ async delete(name) {
72
+ await this.repository().delete({ name });
73
+ }
74
+ }
75
+ exports.TypeOrmRecordStore = TypeOrmRecordStore;
76
+ /** JSON records sealed with the SecretBox; reading a record sealed with another key throws. */
77
+ class SealedRecords {
78
+ store;
79
+ box;
80
+ constructor(store, box) {
81
+ this.store = store;
82
+ this.box = box;
83
+ }
84
+ async read(name) {
85
+ const row = await this.store.get(name);
86
+ if (row === null)
87
+ return null;
88
+ return { data: JSON.parse(this.box.open(name, row.value)), revision: row.revision };
89
+ }
90
+ /** Replaces the record read as `expected` (null: not present); false when it changed meanwhile. */
91
+ async replace(name, expected, data) {
92
+ return this.store.put(name, this.box.seal(name, JSON.stringify(data)), expected?.revision ?? null);
93
+ }
94
+ /** Writes the record whatever it holds now, also over a value sealed with another key. */
95
+ async overwrite(name, data) {
96
+ const sealed = this.box.seal(name, JSON.stringify(data));
97
+ const row = await this.store.get(name);
98
+ if (!await this.store.put(name, sealed, row?.revision ?? null))
99
+ throw new RecordConflict();
100
+ }
101
+ async delete(name) {
102
+ await this.store.delete(name);
103
+ }
104
+ }
105
+ exports.SealedRecords = SealedRecords;
106
+ class RecordConflict extends Error {
107
+ constructor() { super("TLY Pay record changed concurrently"); }
108
+ }
109
+ exports.RecordConflict = RecordConflict;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Public constants of one release, written into the package by tools/write-release-config.mjs: the
3
+ * standard site from the packaging environment and the shared test site from the fixed
4
+ * `release/test-site.json`. Consumers read the Origins of the site in effect through `siteRelease`.
5
+ */
6
+ export type ReleaseConfig = {
7
+ /** TLY Pay app: consent page `/connect/vendure`, account and Payment links. */
8
+ consoleOrigin: string;
9
+ /** Public API of every server-side request (`<origin>/v1/*`). */
10
+ apiOrigin: string;
11
+ /** Checkout Origin: Widget script `<origin>/widget/crypto-pay.js` and Hosted page `<origin>/#payment_id=`. */
12
+ widgetOrigin: string;
13
+ /** The shared test site of Settings > Advanced; `siteRelease` swaps them in for the `test` site. */
14
+ testConsoleOrigin: string;
15
+ testApiOrigin: string;
16
+ testWidgetOrigin: string;
17
+ /** Lifetime of a pending connection authorization. */
18
+ connectionTtlSecs: number;
19
+ /** Age of a `creating` intent before scheduled replay; fallback delay of an early connection check. */
20
+ paymentRecoveryDelaySecs: number;
21
+ /** Deadline for loading and opening the Widget before the storefront falls back to Hosted Checkout. */
22
+ widgetActionTimeoutSecs: number;
23
+ apiTimeoutSecs: number;
24
+ apiMaxResponseBytes: number;
25
+ webhookToleranceSecs: number;
26
+ /** Creation intents and stored Events handled per scheduled run. */
27
+ recoveryBatchSize: number;
28
+ };
29
+ export declare const RELEASE_CONFIG_FILE = "release-config.json";
30
+ export declare const WIDGET_SCRIPT_PATH = "/widget/crypto-pay.js";
31
+ /** Key of each test site Origin in `release/test-site.json`, fixed in the repository. */
32
+ export declare const TEST_SITE_KEYS: {
33
+ readonly testConsoleOrigin: "console_origin";
34
+ readonly testApiOrigin: "api_origin";
35
+ readonly testWidgetOrigin: "widget_origin";
36
+ };
37
+ /** Packaging environment name of each other release constant, shared with the other TLY Pay plugins. */
38
+ export declare const RELEASE_ENV: Record<Exclude<keyof ReleaseConfig, keyof typeof TEST_SITE_KEYS>, string>;
39
+ /**
40
+ * Returns the first invalid key, or null. Packaging and runtime share this rule, so a package
41
+ * can only carry values the runtime accepts.
42
+ */
43
+ export declare function invalidReleaseKey(value: unknown): keyof ReleaseConfig | "shape" | null;
44
+ /** Reads the packaged release constants; a missing or invalid file yields null (fail closed). */
45
+ export declare function loadReleaseConfig(dir: string): ReleaseConfig | null;
46
+ /** The TLY Pay site of Settings > Advanced: the packaged standard site (default) or the shared test site. */
47
+ export declare const SITE_MODES: readonly ["standard", "test"];
48
+ export type SiteMode = typeof SITE_MODES[number];
49
+ /** A stored site value; missing or unknown reads as `standard`. */
50
+ export declare function siteMode(value: unknown): SiteMode;
51
+ /** The release constants with the Origins of `mode` in effect. */
52
+ export declare function siteRelease(release: ReleaseConfig, mode: SiteMode): ReleaseConfig;
53
+ export declare function widgetScriptUrl(release: ReleaseConfig): string;
54
+ /** The packaged release constants of this package, or null for an incomplete installation. */
55
+ export declare function releaseConfig(): ReleaseConfig | null;