@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,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TlyPaySiteSettings = exports.SITE_MODE_KEY = exports.SITE_MODE_FIELD = exports.TlyPayCoinNamesSettings = exports.CHECKOUT_COIN_NAMES_KEY = exports.CHECKOUT_COIN_NAMES_FIELD = exports.TlyPayCheckoutIconSettings = exports.ICON_MARK = exports.CHECKOUT_ICONS_KEY = exports.CHECKOUT_ICONS_FIELD = exports.TlyPayCheckoutSettings = exports.DEFAULT_CHECKOUT_MODE = exports.CHECKOUT_MODES = exports.CHECKOUT_MODE_KEY = exports.CHECKOUT_MODE_FIELD = exports.TlyPayClientRefService = exports.CLIENT_REF_KEY = exports.CLIENT_REF_FIELD = exports.CLIENT_REF_NAMESPACE = void 0;
4
+ const core_1 = require("@vendure/core");
5
+ const contracts_1 = require("./contracts");
6
+ const release_config_1 = require("./release-config");
7
+ exports.CLIENT_REF_NAMESPACE = "tlyPay";
8
+ exports.CLIENT_REF_FIELD = "clientRef";
9
+ exports.CLIENT_REF_KEY = `${exports.CLIENT_REF_NAMESPACE}.${exports.CLIENT_REF_FIELD}`;
10
+ const GLOBAL_SCOPE = "";
11
+ /**
12
+ * Keeps this installation's `client_ref` in the Vendure Settings Store, apart from the API Key and
13
+ * Webhook Secrets, so changing or reconnecting them keeps it. Reads and the first insert use the raw
14
+ * autocommit connection, outside any host request transaction: a request that rolls back after the
15
+ * Payment was created cannot lose the value, and a caller whose insert is ignored reads the committed
16
+ * winner.
17
+ */
18
+ class TlyPayClientRefService {
19
+ connection;
20
+ constructor(connection) {
21
+ this.connection = connection;
22
+ }
23
+ async get() {
24
+ const repository = this.connection.rawConnection.getRepository(core_1.SettingsStoreEntry);
25
+ const stored = await read(repository);
26
+ if (stored !== null)
27
+ return stored;
28
+ await repository.createQueryBuilder()
29
+ .insert().values(new core_1.SettingsStoreEntry({ key: exports.CLIENT_REF_KEY, scope: GLOBAL_SCOPE, value: (0, contracts_1.generateClientRef)() }))
30
+ .orIgnore().execute();
31
+ const created = await read(repository);
32
+ if (created === null)
33
+ throw new TypeError("TLY Pay client_ref was not persisted");
34
+ return created;
35
+ }
36
+ }
37
+ exports.TlyPayClientRefService = TlyPayClientRefService;
38
+ async function read(repository) {
39
+ const entry = await repository.findOne({ where: { key: exports.CLIENT_REF_KEY, scope: GLOBAL_SCOPE } });
40
+ if (entry === null)
41
+ return null;
42
+ if (typeof entry.value !== "string" || !contracts_1.CLIENT_REF.test(entry.value)) {
43
+ throw new TypeError("Stored TLY Pay client_ref is invalid");
44
+ }
45
+ return entry.value;
46
+ }
47
+ exports.CHECKOUT_MODE_FIELD = "checkoutMode";
48
+ exports.CHECKOUT_MODE_KEY = `${exports.CLIENT_REF_NAMESPACE}.${exports.CHECKOUT_MODE_FIELD}`;
49
+ exports.CHECKOUT_MODES = ["hosted", "embedded"];
50
+ /** Vendure storefronts are headless, so new Payments use Hosted Checkout until the merchant opts in. */
51
+ exports.DEFAULT_CHECKOUT_MODE = "hosted";
52
+ /**
53
+ * Keeps the checkout mode of new Payments in the Settings Store. It is independent of the connection,
54
+ * so Disconnect keeps it; an existing intent keeps the mode it was created with.
55
+ */
56
+ class TlyPayCheckoutSettings {
57
+ connection;
58
+ constructor(connection) {
59
+ this.connection = connection;
60
+ }
61
+ async get() {
62
+ const entry = await this.connection.rawConnection.getRepository(core_1.SettingsStoreEntry)
63
+ .findOne({ where: { key: exports.CHECKOUT_MODE_KEY, scope: GLOBAL_SCOPE } });
64
+ return exports.CHECKOUT_MODES.includes(entry?.value) ? entry.value : exports.DEFAULT_CHECKOUT_MODE;
65
+ }
66
+ async set(mode) {
67
+ if (!exports.CHECKOUT_MODES.includes(mode))
68
+ return false;
69
+ await saveSetting(this.connection, exports.CHECKOUT_MODE_KEY, mode);
70
+ return true;
71
+ }
72
+ }
73
+ exports.TlyPayCheckoutSettings = TlyPayCheckoutSettings;
74
+ exports.CHECKOUT_ICONS_FIELD = "checkoutIcons";
75
+ exports.CHECKOUT_ICONS_KEY = `${exports.CLIENT_REF_NAMESPACE}.${exports.CHECKOUT_ICONS_FIELD}`;
76
+ /** A checkout icon mark: the lowercase key of a bundled coin icon. */
77
+ exports.ICON_MARK = /^[a-z0-9_]{1,32}$/;
78
+ /** Trimmed lowercase marks that match `ICON_MARK`, without duplicates, in their first order. */
79
+ function marks(values) {
80
+ return [...new Set(values.map((value) => value.trim().toLowerCase()).filter((value) => exports.ICON_MARK.test(value)))];
81
+ }
82
+ /**
83
+ * Keeps the checkout icon marks chosen in Settings > Checkout appearance in the Settings Store as a JSON
84
+ * array. A missing entry means the merchant never chose and reads as null, which checkout resolves to
85
+ * every coin the Store accepts; an empty array shows no icons. A saved mark is shown whether or not the
86
+ * Store accepts it.
87
+ */
88
+ class TlyPayCheckoutIconSettings {
89
+ connection;
90
+ constructor(connection) {
91
+ this.connection = connection;
92
+ }
93
+ /** The saved marks, or null while no choice was saved. */
94
+ async get() {
95
+ const entry = await this.connection.rawConnection.getRepository(core_1.SettingsStoreEntry)
96
+ .findOne({ where: { key: exports.CHECKOUT_ICONS_KEY, scope: GLOBAL_SCOPE } });
97
+ if (entry === null || !Array.isArray(entry.value))
98
+ return null;
99
+ return marks(entry.value.filter((value) => typeof value === "string"));
100
+ }
101
+ /** Replaces the choice with the sanitized marks; false when the input is not a list of strings. */
102
+ async set(input) {
103
+ if (!Array.isArray(input) || input.some((value) => typeof value !== "string"))
104
+ return false;
105
+ await saveSetting(this.connection, exports.CHECKOUT_ICONS_KEY, marks(input));
106
+ return true;
107
+ }
108
+ }
109
+ exports.TlyPayCheckoutIconSettings = TlyPayCheckoutIconSettings;
110
+ exports.CHECKOUT_COIN_NAMES_FIELD = "checkoutCoinNames";
111
+ exports.CHECKOUT_COIN_NAMES_KEY = `${exports.CLIENT_REF_NAMESPACE}.${exports.CHECKOUT_COIN_NAMES_FIELD}`;
112
+ /**
113
+ * Keeps the "Show coin names under the title" switch of Settings > Checkout appearance in the Settings
114
+ * Store. It is off unless saved on, so checkout shows no text under the title by default.
115
+ */
116
+ class TlyPayCoinNamesSettings {
117
+ connection;
118
+ constructor(connection) {
119
+ this.connection = connection;
120
+ }
121
+ async get() {
122
+ const entry = await this.connection.rawConnection.getRepository(core_1.SettingsStoreEntry)
123
+ .findOne({ where: { key: exports.CHECKOUT_COIN_NAMES_KEY, scope: GLOBAL_SCOPE } });
124
+ return entry?.value === true;
125
+ }
126
+ async set(shown) {
127
+ await saveSetting(this.connection, exports.CHECKOUT_COIN_NAMES_KEY, shown);
128
+ }
129
+ }
130
+ exports.TlyPayCoinNamesSettings = TlyPayCoinNamesSettings;
131
+ exports.SITE_MODE_FIELD = "siteMode";
132
+ exports.SITE_MODE_KEY = `${exports.CLIENT_REF_NAMESPACE}.${exports.SITE_MODE_FIELD}`;
133
+ /**
134
+ * Keeps the TLY Pay site of Settings > Advanced in the Settings Store. Changing it keeps the saved
135
+ * connection; a connection saved for the other site is not used until the store connects again.
136
+ */
137
+ class TlyPaySiteSettings {
138
+ connection;
139
+ constructor(connection) {
140
+ this.connection = connection;
141
+ }
142
+ async get() {
143
+ const entry = await this.connection.rawConnection.getRepository(core_1.SettingsStoreEntry)
144
+ .findOne({ where: { key: exports.SITE_MODE_KEY, scope: GLOBAL_SCOPE } });
145
+ return (0, release_config_1.siteMode)(entry?.value);
146
+ }
147
+ async set(mode) {
148
+ if (!release_config_1.SITE_MODES.includes(mode))
149
+ return false;
150
+ await saveSetting(this.connection, exports.SITE_MODE_KEY, mode);
151
+ return true;
152
+ }
153
+ }
154
+ exports.TlyPaySiteSettings = TlyPaySiteSettings;
155
+ /** Inserts or updates one global Settings Store entry (a JSON value) on the raw autocommit connection. */
156
+ async function saveSetting(connection, key, value) {
157
+ const repository = connection.rawConnection.getRepository(core_1.SettingsStoreEntry);
158
+ const entry = await repository.findOne({ where: { key, scope: GLOBAL_SCOPE } });
159
+ if (entry === null) {
160
+ await repository.createQueryBuilder().insert()
161
+ .values(new core_1.SettingsStoreEntry({ key, scope: GLOBAL_SCOPE, value })).orIgnore().execute();
162
+ }
163
+ await repository.createQueryBuilder().update(core_1.SettingsStoreEntry).set({ value: value })
164
+ .where("key = :key AND scope = :scope", { key, scope: GLOBAL_SCOPE }).execute();
165
+ }
@@ -0,0 +1,65 @@
1
+ import { ConnectionError, ConnectionService } from "./connection";
2
+ import { ExchangedCredentials } from "./public-api";
3
+ import { SealedRecords } from "./records";
4
+ /** Server-side state of one authorization; sealed at rest because it holds the PKCE verifier. */
5
+ export type PendingConnect = {
6
+ stateHash: string;
7
+ verifier: string;
8
+ expiresAt: number;
9
+ userId: string;
10
+ /** Dashboard page that started, where the callback hands `state` and `code` back. */
11
+ adminUrl: string;
12
+ popup: boolean;
13
+ redirectUri: string;
14
+ currency: string;
15
+ code: string | null;
16
+ credentials: ExchangedCredentials | null;
17
+ };
18
+ export type ConnectResult = {
19
+ result: string;
20
+ retry: boolean;
21
+ };
22
+ /**
23
+ * Account connection through the TLY Pay consent page.
24
+ *
25
+ * Start keeps the PKCE verifier, the browser state hash, the starting Administrator, the Dashboard
26
+ * page and whether a popup runs the flow, sealed server-side for the packaged connection TTL; starting
27
+ * again supersedes the pending authorization. The callback URL sent to TLY Pay never changes. TLY Pay
28
+ * returns to `/tly-pay/connect/return`, which needs no session and only forwards `state` and `code`
29
+ * into the Dashboard. The signed-in Administrator who started then completes it: the one-time code is
30
+ * exchanged at `POST /v1/plugins/vendure/exchange` with the installed API Key for lost-response
31
+ * recovery, the credentials are saved with the pending state before they are validated, and a
32
+ * retryable failure keeps the authorization for Retry within the same lifetime.
33
+ */
34
+ export declare class ConnectFlow {
35
+ private readonly records;
36
+ private readonly connections;
37
+ private readonly nowSecs;
38
+ constructor(records: SealedRecords, connections: ConnectionService, nowSecs?: () => number);
39
+ /** Returns the consent page URL to open in the popup or the current tab. */
40
+ start(input: {
41
+ userId: string;
42
+ adminUrl: string;
43
+ popup: boolean;
44
+ currency: string;
45
+ }): Promise<string>;
46
+ /**
47
+ * Where the callback sends the browser: the Dashboard page of the pending authorization with
48
+ * `state` and `code` (empty when cancelled), or with `connection_expired` for a state that is not the
49
+ * current one. Null when nothing is pending.
50
+ */
51
+ returnTarget(state: string, code: string): Promise<string | null>;
52
+ /**
53
+ * Finishes an authorization with the code from the callback, or retries it with the saved code when
54
+ * `code` is null.
55
+ */
56
+ complete(state: string, code: string | null, userId: string): Promise<ConnectResult>;
57
+ private save;
58
+ private pending;
59
+ private matches;
60
+ }
61
+ /**
62
+ * A lost response, an outage or a validation failure the merchant can correct in TLY Pay keeps the
63
+ * authorization; a rejected authorization or binding is final and needs a new connection.
64
+ */
65
+ export declare function retryable(err: ConnectionError): boolean;
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConnectFlow = void 0;
4
+ exports.retryable = retryable;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const connection_1 = require("./connection");
7
+ const public_api_1 = require("./public-api");
8
+ const secret_box_1 = require("./secret-box");
9
+ const STATE = /^[A-Za-z0-9_-]{43}$/;
10
+ /**
11
+ * Account connection through the TLY Pay consent page.
12
+ *
13
+ * Start keeps the PKCE verifier, the browser state hash, the starting Administrator, the Dashboard
14
+ * page and whether a popup runs the flow, sealed server-side for the packaged connection TTL; starting
15
+ * again supersedes the pending authorization. The callback URL sent to TLY Pay never changes. TLY Pay
16
+ * returns to `/tly-pay/connect/return`, which needs no session and only forwards `state` and `code`
17
+ * into the Dashboard. The signed-in Administrator who started then completes it: the one-time code is
18
+ * exchanged at `POST /v1/plugins/vendure/exchange` with the installed API Key for lost-response
19
+ * recovery, the credentials are saved with the pending state before they are validated, and a
20
+ * retryable failure keeps the authorization for Retry within the same lifetime.
21
+ */
22
+ class ConnectFlow {
23
+ records;
24
+ connections;
25
+ nowSecs;
26
+ constructor(records, connections, nowSecs = () => Math.floor(Date.now() / 1000)) {
27
+ this.records = records;
28
+ this.connections = connections;
29
+ this.nowSecs = nowSecs;
30
+ }
31
+ /** Returns the consent page URL to open in the popup or the current tab. */
32
+ async start(input) {
33
+ const release = await this.connections.release();
34
+ if (release === null)
35
+ throw new connection_1.ConnectionError("connection_unavailable");
36
+ if (input.userId === "" || !validAdminUrl(input.adminUrl))
37
+ throw new connection_1.ConnectionError("forbidden");
38
+ if (!/^[A-Z]{3}$/.test(input.currency))
39
+ throw new connection_1.ConnectionError("currency_mismatch");
40
+ const urls = this.connections.urls();
41
+ const existing = await this.connections.get();
42
+ const state = token();
43
+ const verifier = token();
44
+ const pending = {
45
+ stateHash: sha256(state), verifier, expiresAt: this.nowSecs() + release.connectionTtlSecs,
46
+ userId: input.userId, adminUrl: input.adminUrl, popup: input.popup, redirectUri: urls.callback,
47
+ currency: input.currency, code: null, credentials: null,
48
+ };
49
+ await this.records.overwrite("pending_connect", pending);
50
+ const query = new URLSearchParams({
51
+ state,
52
+ code_challenge: (0, node_crypto_1.createHash)("sha256").update(verifier).digest("base64url"),
53
+ redirect_uri: urls.callback,
54
+ webhook_url: urls.webhook,
55
+ currency: input.currency,
56
+ bound_store_id: existing?.storeId ?? "",
57
+ });
58
+ return `${release.consoleOrigin}/connect/${public_api_1.PLATFORM}?${query.toString()}`;
59
+ }
60
+ /**
61
+ * Where the callback sends the browser: the Dashboard page of the pending authorization with
62
+ * `state` and `code` (empty when cancelled), or with `connection_expired` for a state that is not the
63
+ * current one. Null when nothing is pending.
64
+ */
65
+ async returnTarget(state, code) {
66
+ const pending = await this.pending();
67
+ if (pending === null)
68
+ return null;
69
+ const query = new URLSearchParams({ tly_popup: pending.data.popup ? "1" : "0" });
70
+ if (this.matches(pending.data, state)) {
71
+ query.set("tly_state", state);
72
+ query.set("tly_code", /^[\x21-\x7e]{1,512}$/.test(code) ? code : "");
73
+ }
74
+ else {
75
+ query.set("tly_result", "connection_expired");
76
+ }
77
+ return `${pending.data.adminUrl}?${query.toString()}`;
78
+ }
79
+ /**
80
+ * Finishes an authorization with the code from the callback, or retries it with the saved code when
81
+ * `code` is null.
82
+ */
83
+ async complete(state, code, userId) {
84
+ let pending = await this.pending();
85
+ if (pending === null || !this.matches(pending.data, state) || userId === "" || pending.data.userId !== userId) {
86
+ return { result: "connection_expired", retry: false };
87
+ }
88
+ if (code === "") {
89
+ await this.records.delete("pending_connect");
90
+ return { result: "connection_cancelled", retry: false };
91
+ }
92
+ const saved = pending.data.code;
93
+ if (code === null ? saved === null : saved !== null && saved !== code) {
94
+ return { result: "connection_expired", retry: false };
95
+ }
96
+ try {
97
+ if (saved === null)
98
+ pending = await this.save(pending, { ...pending.data, code });
99
+ if (pending.data.credentials === null) {
100
+ const existing = await this.connections.get();
101
+ let credentials;
102
+ try {
103
+ credentials = await (await this.connections.api()).exchangeConnection(pending.data.code, pending.data.verifier, pending.data.redirectUri, existing?.apiKey ?? "");
104
+ }
105
+ catch (error) {
106
+ if (error instanceof public_api_1.TlyApiError)
107
+ throw connection_1.ConnectionError.fromApi(error);
108
+ throw error;
109
+ }
110
+ pending = await this.save(pending, { ...pending.data, credentials });
111
+ }
112
+ const latest = await this.pending();
113
+ if (latest === null || !this.matches(latest.data, state))
114
+ return { result: "connection_expired", retry: false };
115
+ await this.connections.install(pending.data.credentials, pending.data.currency);
116
+ }
117
+ catch (error) {
118
+ if (!(error instanceof connection_1.ConnectionError))
119
+ throw error;
120
+ if (!retryable(error)) {
121
+ await this.records.delete("pending_connect");
122
+ return { result: error.code, retry: false };
123
+ }
124
+ return { result: error.code, retry: true };
125
+ }
126
+ await this.records.delete("pending_connect");
127
+ return { result: "saved", retry: false };
128
+ }
129
+ async save(current, next) {
130
+ if (!await this.records.replace("pending_connect", current, next))
131
+ throw new connection_1.ConnectionError("connection_expired");
132
+ return { data: next, revision: current.revision + 1 };
133
+ }
134
+ async pending() {
135
+ try {
136
+ return await this.records.read("pending_connect");
137
+ }
138
+ catch (error) {
139
+ if (error instanceof secret_box_1.SealedValueUnreadable)
140
+ return null;
141
+ throw error;
142
+ }
143
+ }
144
+ matches(pending, state) {
145
+ if (!STATE.test(state))
146
+ return false;
147
+ const expected = Buffer.from(pending.stateHash, "hex");
148
+ const actual = Buffer.from(sha256(state), "hex");
149
+ return expected.byteLength === actual.byteLength && (0, node_crypto_1.timingSafeEqual)(expected, actual)
150
+ && pending.expiresAt > this.nowSecs();
151
+ }
152
+ }
153
+ exports.ConnectFlow = ConnectFlow;
154
+ /**
155
+ * A lost response, an outage or a validation failure the merchant can correct in TLY Pay keeps the
156
+ * authorization; a rejected authorization or binding is final and needs a new connection.
157
+ */
158
+ function retryable(err) {
159
+ return !err.rejected && !err.code.startsWith("platform_")
160
+ && !["unauthorized", "forbidden", "not_found"].includes(err.code);
161
+ }
162
+ function validAdminUrl(value) {
163
+ try {
164
+ const url = new URL(value);
165
+ return (url.protocol === "https:" || url.protocol === "http:") && url.hostname !== "" && !url.username
166
+ && !url.password && !url.search && !url.hash && value.length <= 2048;
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ }
172
+ function token() {
173
+ return (0, node_crypto_1.randomBytes)(32).toString("base64url");
174
+ }
175
+ function sha256(value) {
176
+ return (0, node_crypto_1.createHash)("sha256").update(value).digest("hex");
177
+ }
@@ -0,0 +1,28 @@
1
+ import { SignedRequest } from "./signed-webhook";
2
+ /**
3
+ * TLY Pay sends one signed `endpoint.ping` to this server's Webhook when a connection is established.
4
+ * The plugin answers with its facts and an acknowledgment signed with the Secret that verified the
5
+ * request, which proves that this plugin, not a cache or a security page, answered. Nothing is stored.
6
+ */
7
+ export declare const PLATFORM = "vendure";
8
+ export declare const ACK_HEADER = "X-TLY-Webhook-Ack";
9
+ /** The facts of the answer; `gatewayEnabled` is the native payment method switch. */
10
+ export type ConnectionFacts = {
11
+ pluginVersion: string;
12
+ platformVersion: string;
13
+ gatewayEnabled: boolean;
14
+ };
15
+ /** An HTTP answer the Webhook route writes as is: status, headers and the exact body bytes. */
16
+ export type WebhookAnswer = {
17
+ status: number;
18
+ headers?: Record<string, string>;
19
+ body?: Buffer;
20
+ };
21
+ /** `{"event_id","platform","plugin_version","platform_version","gateway_enabled"}`, in this order. */
22
+ export declare function answerBody(eventId: string, facts: ConnectionFacts): string;
23
+ /** `v1=` and the lowercase hex HMAC-SHA256 over `<request timestamp>.<event id>.<exact body>`. */
24
+ export declare function ackHeader(secret: string, timestamp: string, eventId: string, body: string): string;
25
+ /** The `200` answer of a verified connection check. */
26
+ export declare function connectionCheckAnswer(request: SignedRequest, facts: ConnectionFacts): WebhookAnswer;
27
+ /** This plugin's version from its package manifest, one directory above `src/` and `dist/`. */
28
+ export declare function pluginVersion(): string;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ACK_HEADER = exports.PLATFORM = void 0;
4
+ exports.answerBody = answerBody;
5
+ exports.ackHeader = ackHeader;
6
+ exports.connectionCheckAnswer = connectionCheckAnswer;
7
+ exports.pluginVersion = pluginVersion;
8
+ const node_crypto_1 = require("node:crypto");
9
+ const node_fs_1 = require("node:fs");
10
+ const node_path_1 = require("node:path");
11
+ /**
12
+ * TLY Pay sends one signed `endpoint.ping` to this server's Webhook when a connection is established.
13
+ * The plugin answers with its facts and an acknowledgment signed with the Secret that verified the
14
+ * request, which proves that this plugin, not a cache or a security page, answered. Nothing is stored.
15
+ */
16
+ exports.PLATFORM = "vendure";
17
+ exports.ACK_HEADER = "X-TLY-Webhook-Ack";
18
+ /** `{"event_id","platform","plugin_version","platform_version","gateway_enabled"}`, in this order. */
19
+ function answerBody(eventId, facts) {
20
+ return JSON.stringify({ event_id: eventId, platform: exports.PLATFORM, plugin_version: facts.pluginVersion,
21
+ platform_version: facts.platformVersion, gateway_enabled: facts.gatewayEnabled });
22
+ }
23
+ /** `v1=` and the lowercase hex HMAC-SHA256 over `<request timestamp>.<event id>.<exact body>`. */
24
+ function ackHeader(secret, timestamp, eventId, body) {
25
+ return "v1=" + (0, node_crypto_1.createHmac)("sha256", secret).update(`${timestamp}.${eventId}.`).update(body, "utf8").digest("hex");
26
+ }
27
+ /** The `200` answer of a verified connection check. */
28
+ function connectionCheckAnswer(request, facts) {
29
+ const answer = answerBody(request.eventId, facts);
30
+ const body = Buffer.from(answer, "utf8");
31
+ return {
32
+ status: 200,
33
+ headers: {
34
+ "Content-Type": "application/json", "Content-Length": String(body.byteLength), "Cache-Control": "no-store",
35
+ [exports.ACK_HEADER]: ackHeader(request.secret, request.timestamp, request.eventId, answer),
36
+ },
37
+ body,
38
+ };
39
+ }
40
+ /** This plugin's version from its package manifest, one directory above `src/` and `dist/`. */
41
+ function pluginVersion() {
42
+ try {
43
+ const version = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf8")).version;
44
+ return typeof version === "string" ? version : "";
45
+ }
46
+ catch {
47
+ return "";
48
+ }
49
+ }
@@ -0,0 +1,140 @@
1
+ import { PaymentAsset } from "./contracts";
2
+ import { ExchangedCredentials, PublicApiClient, TlyApiError } from "./public-api";
3
+ import { SealedRecords } from "./records";
4
+ import { ReleaseConfig } from "./release-config";
5
+ /** Path suffixes registered for Vendure in the platform connection registry. */
6
+ export declare const CALLBACK_PATH = "/tly-pay/connect/return";
7
+ export declare const WEBHOOK_PATH = "/tly-pay/webhook";
8
+ /**
9
+ * The saved account connection; sealed at rest because it holds the API Key and Webhook Secrets.
10
+ * `apiOrigin` is the API Origin of the site it was saved for.
11
+ */
12
+ export type Connection = {
13
+ apiOrigin: string;
14
+ apiKey: string;
15
+ endpointId: string;
16
+ webhookSecret: string;
17
+ pendingWebhookSecret: string;
18
+ webhookUrl: string;
19
+ storeId: string;
20
+ displayName: string;
21
+ storeStatus: string;
22
+ sourceKind: string;
23
+ sourceCurrency: string;
24
+ sourceDecimals: number;
25
+ merchantDomain: string;
26
+ paymentsReady: boolean;
27
+ paymentAssets: PaymentAsset[];
28
+ /** False only after a definitive rejection; a transient failure keeps it. */
29
+ ready: boolean;
30
+ lastErr: string;
31
+ validatedAt: number;
32
+ /** Earlier connection check requested after a transient failure (Unix seconds), or null. */
33
+ earlyCheckAt: number | null;
34
+ };
35
+ /**
36
+ * A connection or Store validation outcome with a stable, non-sensitive code shown by the Dashboard.
37
+ * `retryable` keeps a saved connection ready and asks for an earlier check; `rejected` marks a
38
+ * definitive 4xx rejection of the request.
39
+ */
40
+ export declare class ConnectionError extends Error {
41
+ readonly code: string;
42
+ readonly retryable: boolean;
43
+ readonly retryAfterSecs: number | null;
44
+ readonly rejected: boolean;
45
+ constructor(code: string, retryable?: boolean, retryAfterSecs?: number | null, rejected?: boolean);
46
+ static fromApi(err: TlyApiError, code?: string): ConnectionError;
47
+ }
48
+ /** Browser-safe connection view without Secrets. `state`: off, ok, pending (wallet setup needed) or warn. */
49
+ export type ConnectionStatus = {
50
+ connected: boolean;
51
+ state: "off" | "ok" | "pending" | "warn";
52
+ displayName: string;
53
+ storeId: string;
54
+ currency: string;
55
+ merchantDomain: string;
56
+ paymentsReady: boolean;
57
+ paymentAssets: PaymentAsset[];
58
+ lastErr: string;
59
+ /** Ready, but the latest check failed transiently; checkout stays available. */
60
+ unverified: boolean;
61
+ validatedAt: number;
62
+ webhookUrl: string;
63
+ };
64
+ /** The exact callback and Webhook URLs under the host's public URL, as the registry requires them. */
65
+ export declare function connectionUrls(publicUrl: string): {
66
+ callback: string;
67
+ webhook: string;
68
+ };
69
+ export type ConnectionDeps = {
70
+ records: SealedRecords;
71
+ /** The release constants with the Origins of the site in effect, or null for an incomplete release. */
72
+ release: () => Promise<ReleaseConfig | null>;
73
+ publicUrl: string;
74
+ api: (apiKey: string, release: ReleaseConfig) => PublicApiClient;
75
+ nowSecs?: () => number;
76
+ };
77
+ /**
78
+ * Installs, rechecks and withdraws the connection of this Vendure installation.
79
+ *
80
+ * Install validates the exchanged credentials against `GET /v1/store` and the Webhook Endpoint, saves
81
+ * them and synchronizes the signing Secrets (saved before they are acknowledged). The check runs
82
+ * hourly and when the Dashboard opens the Settings tab. Only a definitive rejection (credentials,
83
+ * Store, currency, Endpoint binding) withdraws checkout; a transient failure (408, 425, 429, 5xx,
84
+ * timeout, network) keeps the stored readiness, records the code and asks for an earlier check after
85
+ * the announced `Retry-After` or the packaged payment recovery delay. A Store without a verified
86
+ * wallet (`payments_ready: false`) stays connected but is not eligible at checkout until a later
87
+ * check reads it as ready.
88
+ *
89
+ * A connection saved for the other TLY Pay site (Settings > Advanced) is kept but not used: it reads
90
+ * as absent until the store connects again, which replaces it, or the site is switched back.
91
+ */
92
+ export declare class ConnectionService {
93
+ private readonly deps;
94
+ private readonly now;
95
+ constructor(deps: ConnectionDeps);
96
+ release(): Promise<ReleaseConfig | null>;
97
+ urls(): {
98
+ callback: string;
99
+ webhook: string;
100
+ };
101
+ api(apiKey?: string): Promise<PublicApiClient>;
102
+ /**
103
+ * The saved connection of the site in effect, or null; a value that cannot be decrypted or that was
104
+ * saved for the other site reads as null.
105
+ */
106
+ get(): Promise<Connection | null>;
107
+ /** Validates and installs exchanged credentials for the requested currency, then synchronizes Secrets. */
108
+ install(credentials: ExchangedCredentials, currency: string): Promise<void>;
109
+ /** Revalidates the saved connection without discarding it; see the class comment for the outcome. */
110
+ refresh(): Promise<void>;
111
+ /** Whether an earlier check requested after a transient failure is due. */
112
+ earlyCheckDue(): Promise<boolean>;
113
+ /**
114
+ * Saves the authoritative Secrets before acknowledging them, so TLY Pay can confirm a rotation only
115
+ * after this shop accepted the new Secret.
116
+ */
117
+ synchronize(): Promise<void>;
118
+ /** Forgets the local connection and any pending authorization; Payment records and `client_ref` stay. */
119
+ disconnect(): Promise<void>;
120
+ /**
121
+ * Whether checkout may offer the payment method: a complete release and a ready connection of an
122
+ * active fiat Store in the order currency with a verified wallet.
123
+ */
124
+ available(currency: string): Promise<Connection | null>;
125
+ status(): Promise<ConnectionStatus>;
126
+ /**
127
+ * The stored record of the site in effect: null when absent, without a complete release or saved for
128
+ * the other site; `data` is null when it exists but cannot be decrypted with the current key.
129
+ */
130
+ private snapshot;
131
+ private client;
132
+ private validate;
133
+ /**
134
+ * Records a failed check against the connection it ran on: a definitive rejection withdraws checkout;
135
+ * a transient failure keeps readiness and asks for an earlier check.
136
+ */
137
+ private recordFailure;
138
+ }
139
+ export declare function validateCredentials(credentials: ExchangedCredentials): void;
140
+ export declare function toConnectionError(error: unknown): ConnectionError;