@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.
- package/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +192 -2
- package/assets/coins/arb.svg +10 -0
- package/assets/coins/base.svg +4 -0
- package/assets/coins/bln.svg +4 -0
- package/assets/coins/bnb.svg +13 -0
- package/assets/coins/btc.svg +1 -0
- package/assets/coins/busd.svg +7 -0
- package/assets/coins/coin.svg +1 -0
- package/assets/coins/dai.svg +1 -0
- package/assets/coins/doge.svg +109 -0
- package/assets/coins/eth.svg +10 -0
- package/assets/coins/jst.svg +11 -0
- package/assets/coins/link.svg +4 -0
- package/assets/coins/ltc.svg +4 -0
- package/assets/coins/op.svg +12 -0
- package/assets/coins/pol.svg +11 -0
- package/assets/coins/shib.svg +18 -0
- package/assets/coins/sol.svg +15 -0
- package/assets/coins/sun.svg +71 -0
- package/assets/coins/trx.svg +4 -0
- package/assets/coins/uni.svg +10 -0
- package/assets/coins/usdc.svg +6 -0
- package/assets/coins/usdd.svg +18 -0
- package/assets/coins/usdt.svg +1 -0
- package/assets/coins/wbtc.svg +16 -0
- package/assets/coins/weth.svg +17 -0
- package/assets/tly-pay-mark.svg +31 -0
- package/dashboard/api.ts +167 -0
- package/dashboard/appearance.tsx +253 -0
- package/dashboard/banner.tsx +72 -0
- package/dashboard/i18n/en.po +584 -0
- package/dashboard/index.tsx +33 -0
- package/dashboard/logic.ts +219 -0
- package/dashboard/messages.tsx +90 -0
- package/dashboard/notice.tsx +15 -0
- package/dashboard/order-block.tsx +21 -0
- package/dashboard/orders.tsx +246 -0
- package/dashboard/page.tsx +174 -0
- package/dashboard/settings.tsx +186 -0
- package/dashboard/use-connect.ts +46 -0
- package/dist/api.d.ts +169 -0
- package/dist/api.js +541 -0
- package/dist/client-ref.d.ts +75 -0
- package/dist/client-ref.js +165 -0
- package/dist/connect-flow.d.ts +65 -0
- package/dist/connect-flow.js +177 -0
- package/dist/connection-check.d.ts +28 -0
- package/dist/connection-check.js +49 -0
- package/dist/connection.d.ts +140 -0
- package/dist/connection.js +361 -0
- package/dist/contracts.d.ts +66 -0
- package/dist/contracts.js +151 -0
- package/dist/creation-service.d.ts +136 -0
- package/dist/creation-service.js +242 -0
- package/dist/handler.d.ts +13 -0
- package/dist/handler.js +45 -0
- package/dist/hosted-checkout.d.ts +3 -0
- package/dist/hosted-checkout.js +25 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +32 -0
- package/dist/ownership.d.ts +38 -0
- package/dist/ownership.js +38 -0
- package/dist/payment-sync.d.ts +45 -0
- package/dist/payment-sync.js +111 -0
- package/dist/persistence.d.ts +104 -0
- package/dist/persistence.js +405 -0
- package/dist/plugin.d.ts +26 -0
- package/dist/plugin.js +112 -0
- package/dist/public-api.d.ts +56 -0
- package/dist/public-api.js +221 -0
- package/dist/records.d.ts +53 -0
- package/dist/records.js +109 -0
- package/dist/release-config.d.ts +55 -0
- package/dist/release-config.js +107 -0
- package/dist/release-config.json +15 -0
- package/dist/secret-box.d.ts +19 -0
- package/dist/secret-box.js +65 -0
- package/dist/service.d.ts +267 -0
- package/dist/service.js +788 -0
- package/dist/signed-webhook.d.ts +67 -0
- package/dist/signed-webhook.js +119 -0
- package/dist/storefront/checkout.d.mts +86 -0
- package/dist/storefront/checkout.mjs +149 -0
- package/package.json +97 -4
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ConnectionService = exports.ConnectionError = exports.WEBHOOK_PATH = exports.CALLBACK_PATH = void 0;
|
|
4
|
+
exports.connectionUrls = connectionUrls;
|
|
5
|
+
exports.validateCredentials = validateCredentials;
|
|
6
|
+
exports.toConnectionError = toConnectionError;
|
|
7
|
+
const node_net_1 = require("node:net");
|
|
8
|
+
const contracts_1 = require("./contracts");
|
|
9
|
+
const public_api_1 = require("./public-api");
|
|
10
|
+
const records_1 = require("./records");
|
|
11
|
+
const secret_box_1 = require("./secret-box");
|
|
12
|
+
/** Path suffixes registered for Vendure in the platform connection registry. */
|
|
13
|
+
exports.CALLBACK_PATH = "/tly-pay/connect/return";
|
|
14
|
+
exports.WEBHOOK_PATH = "/tly-pay/webhook";
|
|
15
|
+
/**
|
|
16
|
+
* A connection or Store validation outcome with a stable, non-sensitive code shown by the Dashboard.
|
|
17
|
+
* `retryable` keeps a saved connection ready and asks for an earlier check; `rejected` marks a
|
|
18
|
+
* definitive 4xx rejection of the request.
|
|
19
|
+
*/
|
|
20
|
+
class ConnectionError extends Error {
|
|
21
|
+
code;
|
|
22
|
+
retryable;
|
|
23
|
+
retryAfterSecs;
|
|
24
|
+
rejected;
|
|
25
|
+
constructor(code, retryable = false, retryAfterSecs = null, rejected = false) {
|
|
26
|
+
super(code);
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.retryable = retryable;
|
|
29
|
+
this.retryAfterSecs = retryAfterSecs;
|
|
30
|
+
this.rejected = rejected;
|
|
31
|
+
}
|
|
32
|
+
static fromApi(err, code) {
|
|
33
|
+
return new ConnectionError(code ?? err.code, err.retryable, err.retryAfterSecs, !err.retryable && err.httpStatus !== null && err.httpStatus >= 400 && err.httpStatus < 500);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
exports.ConnectionError = ConnectionError;
|
|
37
|
+
/** The exact callback and Webhook URLs under the host's public URL, as the registry requires them. */
|
|
38
|
+
function connectionUrls(publicUrl) {
|
|
39
|
+
let url;
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(publicUrl);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new ConnectionError("https_required");
|
|
45
|
+
}
|
|
46
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash
|
|
47
|
+
|| url.port !== "" && url.port !== "443" || (0, node_net_1.isIP)(url.hostname.replace(/^\[|\]$/g, "")) !== 0
|
|
48
|
+
|| !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(url.hostname)) {
|
|
49
|
+
throw new ConnectionError("https_required");
|
|
50
|
+
}
|
|
51
|
+
const base = `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
52
|
+
return { callback: base + exports.CALLBACK_PATH, webhook: base + exports.WEBHOOK_PATH };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Installs, rechecks and withdraws the connection of this Vendure installation.
|
|
56
|
+
*
|
|
57
|
+
* Install validates the exchanged credentials against `GET /v1/store` and the Webhook Endpoint, saves
|
|
58
|
+
* them and synchronizes the signing Secrets (saved before they are acknowledged). The check runs
|
|
59
|
+
* hourly and when the Dashboard opens the Settings tab. Only a definitive rejection (credentials,
|
|
60
|
+
* Store, currency, Endpoint binding) withdraws checkout; a transient failure (408, 425, 429, 5xx,
|
|
61
|
+
* timeout, network) keeps the stored readiness, records the code and asks for an earlier check after
|
|
62
|
+
* the announced `Retry-After` or the packaged payment recovery delay. A Store without a verified
|
|
63
|
+
* wallet (`payments_ready: false`) stays connected but is not eligible at checkout until a later
|
|
64
|
+
* check reads it as ready.
|
|
65
|
+
*
|
|
66
|
+
* A connection saved for the other TLY Pay site (Settings > Advanced) is kept but not used: it reads
|
|
67
|
+
* as absent until the store connects again, which replaces it, or the site is switched back.
|
|
68
|
+
*/
|
|
69
|
+
class ConnectionService {
|
|
70
|
+
deps;
|
|
71
|
+
now;
|
|
72
|
+
constructor(deps) {
|
|
73
|
+
this.deps = deps;
|
|
74
|
+
this.now = deps.nowSecs ?? (() => Math.floor(Date.now() / 1000));
|
|
75
|
+
}
|
|
76
|
+
release() {
|
|
77
|
+
return this.deps.release();
|
|
78
|
+
}
|
|
79
|
+
urls() {
|
|
80
|
+
return connectionUrls(this.deps.publicUrl);
|
|
81
|
+
}
|
|
82
|
+
async api(apiKey = "") {
|
|
83
|
+
return this.client(await this.deps.release(), apiKey);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The saved connection of the site in effect, or null; a value that cannot be decrypted or that was
|
|
87
|
+
* saved for the other site reads as null.
|
|
88
|
+
*/
|
|
89
|
+
async get() {
|
|
90
|
+
return (await this.snapshot(await this.deps.release()))?.data ?? null;
|
|
91
|
+
}
|
|
92
|
+
/** Validates and installs exchanged credentials for the requested currency, then synchronizes Secrets. */
|
|
93
|
+
async install(credentials, currency) {
|
|
94
|
+
validateCredentials(credentials);
|
|
95
|
+
const urls = this.urls();
|
|
96
|
+
const release = await this.deps.release();
|
|
97
|
+
const api = this.client(release, credentials.apiKey);
|
|
98
|
+
const existing = await this.snapshot(release);
|
|
99
|
+
let store;
|
|
100
|
+
let secrets;
|
|
101
|
+
try {
|
|
102
|
+
store = await api.getStore();
|
|
103
|
+
validateStore(store, currency);
|
|
104
|
+
if (existing !== null && existing.data !== null && existing.data.storeId !== store.storeId) {
|
|
105
|
+
throw new ConnectionError("store_identity_mismatch");
|
|
106
|
+
}
|
|
107
|
+
secrets = await verifySecrets(api, credentials.endpointId, credentials.webhookSecret, credentials.pendingWebhookSecret);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
throw toConnectionError(error);
|
|
111
|
+
}
|
|
112
|
+
const connection = {
|
|
113
|
+
apiOrigin: release.apiOrigin, apiKey: credentials.apiKey, endpointId: credentials.endpointId,
|
|
114
|
+
webhookSecret: secrets[0], pendingWebhookSecret: secrets[1], webhookUrl: urls.webhook,
|
|
115
|
+
...storeFields(store), ready: true, lastErr: "", validatedAt: this.now(), earlyCheckAt: null,
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
if (existing !== null && existing.data !== null) {
|
|
119
|
+
if (!await this.deps.records.replace("connection", existing, connection))
|
|
120
|
+
throw new ConnectionError("persistence_failed");
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
// Nothing usable is saved: no record, one sealed with another key or one of the other site.
|
|
124
|
+
await this.deps.records.overwrite("connection", connection);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error instanceof records_1.RecordConflict)
|
|
129
|
+
throw new ConnectionError("persistence_failed");
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
await this.synchronize();
|
|
133
|
+
}
|
|
134
|
+
/** Revalidates the saved connection without discarding it; see the class comment for the outcome. */
|
|
135
|
+
async refresh() {
|
|
136
|
+
const release = await this.deps.release();
|
|
137
|
+
const current = await this.snapshot(release);
|
|
138
|
+
if (current === null || current.data === null)
|
|
139
|
+
return;
|
|
140
|
+
let candidate;
|
|
141
|
+
try {
|
|
142
|
+
candidate = await this.validate(current.data, release);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
await this.recordFailure(current.data, toConnectionError(error), release);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (!await this.deps.records.replace("connection", current, candidate))
|
|
149
|
+
return;
|
|
150
|
+
try {
|
|
151
|
+
await this.synchronize();
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
const latest = await this.get();
|
|
155
|
+
if (latest !== null)
|
|
156
|
+
await this.recordFailure(latest, toConnectionError(error), release);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Whether an earlier check requested after a transient failure is due. */
|
|
160
|
+
async earlyCheckDue() {
|
|
161
|
+
const connection = await this.get();
|
|
162
|
+
return connection !== null && connection.earlyCheckAt !== null && connection.earlyCheckAt <= this.now();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Saves the authoritative Secrets before acknowledging them, so TLY Pay can confirm a rotation only
|
|
166
|
+
* after this shop accepted the new Secret.
|
|
167
|
+
*/
|
|
168
|
+
async synchronize() {
|
|
169
|
+
const release = await this.deps.release();
|
|
170
|
+
const current = await this.snapshot(release);
|
|
171
|
+
if (current === null || current.data === null)
|
|
172
|
+
throw new ConnectionError("api_key_required");
|
|
173
|
+
const connection = current.data;
|
|
174
|
+
const api = this.client(release, connection.apiKey);
|
|
175
|
+
try {
|
|
176
|
+
const result = await api.synchronizeConnection(connection.endpointId, connection.webhookUrl, connection.pendingWebhookSecret || connection.webhookSecret, false);
|
|
177
|
+
validateCredentials({ apiKey: connection.apiKey, endpointId: connection.endpointId,
|
|
178
|
+
webhookSecret: result.webhookSecret, pendingWebhookSecret: result.pendingWebhookSecret });
|
|
179
|
+
const candidate = { ...connection, ...result };
|
|
180
|
+
if (!await this.deps.records.replace("connection", current, candidate)) {
|
|
181
|
+
throw new ConnectionError("persistence_failed");
|
|
182
|
+
}
|
|
183
|
+
await api.synchronizeConnection(candidate.endpointId, candidate.webhookUrl, candidate.pendingWebhookSecret || candidate.webhookSecret, true);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
throw toConnectionError(error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Forgets the local connection and any pending authorization; Payment records and `client_ref` stay. */
|
|
190
|
+
async disconnect() {
|
|
191
|
+
await this.deps.records.delete("pending_connect");
|
|
192
|
+
await this.deps.records.delete("connection");
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Whether checkout may offer the payment method: a complete release and a ready connection of an
|
|
196
|
+
* active fiat Store in the order currency with a verified wallet.
|
|
197
|
+
*/
|
|
198
|
+
async available(currency) {
|
|
199
|
+
const connection = await this.get();
|
|
200
|
+
return connection !== null && connection.ready && connection.paymentsReady && connection.storeStatus === "active"
|
|
201
|
+
&& connection.sourceKind === "fiat" && connection.sourceCurrency === currency ? connection : null;
|
|
202
|
+
}
|
|
203
|
+
async status() {
|
|
204
|
+
let snapshot;
|
|
205
|
+
try {
|
|
206
|
+
snapshot = await this.snapshot(await this.deps.release());
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (!(error instanceof secret_box_1.SealedValueUnreadable))
|
|
210
|
+
throw error;
|
|
211
|
+
snapshot = { data: null, revision: 0 };
|
|
212
|
+
}
|
|
213
|
+
const empty = { connected: false, state: "off", displayName: "", storeId: "", currency: "",
|
|
214
|
+
merchantDomain: "", paymentsReady: false, paymentAssets: [], lastErr: "", unverified: false, validatedAt: 0,
|
|
215
|
+
webhookUrl: "" };
|
|
216
|
+
if (snapshot === null)
|
|
217
|
+
return empty;
|
|
218
|
+
const binding = snapshot.data;
|
|
219
|
+
if (binding === null)
|
|
220
|
+
return { ...empty, connected: true, state: "warn", lastErr: "connection_unreadable" };
|
|
221
|
+
return {
|
|
222
|
+
connected: true,
|
|
223
|
+
state: !binding.ready ? "warn" : binding.paymentsReady ? "ok" : "pending",
|
|
224
|
+
displayName: binding.displayName, storeId: binding.storeId, currency: binding.sourceCurrency,
|
|
225
|
+
merchantDomain: binding.merchantDomain, paymentsReady: binding.paymentsReady,
|
|
226
|
+
paymentAssets: binding.paymentAssets, lastErr: binding.lastErr,
|
|
227
|
+
unverified: binding.ready && binding.lastErr !== "", validatedAt: binding.validatedAt,
|
|
228
|
+
webhookUrl: binding.webhookUrl,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* The stored record of the site in effect: null when absent, without a complete release or saved for
|
|
233
|
+
* the other site; `data` is null when it exists but cannot be decrypted with the current key.
|
|
234
|
+
*/
|
|
235
|
+
async snapshot(release) {
|
|
236
|
+
let stored;
|
|
237
|
+
try {
|
|
238
|
+
stored = await this.deps.records.read("connection");
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (error instanceof secret_box_1.SealedValueUnreadable)
|
|
242
|
+
return { data: null, revision: -1 };
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
return stored !== null && release !== null && stored.data.apiOrigin === release.apiOrigin ? stored : null;
|
|
246
|
+
}
|
|
247
|
+
client(release, apiKey) {
|
|
248
|
+
if (release === null)
|
|
249
|
+
throw new ConnectionError("connection_unavailable");
|
|
250
|
+
return this.deps.api(apiKey, release);
|
|
251
|
+
}
|
|
252
|
+
async validate(current, release) {
|
|
253
|
+
if (this.urls().webhook !== current.webhookUrl)
|
|
254
|
+
throw new ConnectionError("webhook_url_changed");
|
|
255
|
+
const api = this.client(release, current.apiKey);
|
|
256
|
+
const store = await api.getStore();
|
|
257
|
+
validateStore(store, current.sourceCurrency);
|
|
258
|
+
if (store.storeId !== current.storeId)
|
|
259
|
+
throw new ConnectionError("store_identity_mismatch");
|
|
260
|
+
const [active, pending] = await verifySecrets(api, current.endpointId, current.webhookSecret, current.pendingWebhookSecret);
|
|
261
|
+
return { ...current, ...storeFields(store), webhookSecret: active, pendingWebhookSecret: pending, ready: true,
|
|
262
|
+
lastErr: "", validatedAt: this.now(), earlyCheckAt: null };
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Records a failed check against the connection it ran on: a definitive rejection withdraws checkout;
|
|
266
|
+
* a transient failure keeps readiness and asks for an earlier check.
|
|
267
|
+
*/
|
|
268
|
+
async recordFailure(checked, err, release) {
|
|
269
|
+
const latest = await this.deps.records.read("connection");
|
|
270
|
+
if (latest === null || latest.data.apiKey !== checked.apiKey || latest.data.endpointId !== checked.endpointId)
|
|
271
|
+
return;
|
|
272
|
+
const delay = err.retryAfterSecs ?? release?.paymentRecoveryDelaySecs ?? null;
|
|
273
|
+
await this.deps.records.replace("connection", latest, {
|
|
274
|
+
...latest.data,
|
|
275
|
+
lastErr: /^[a-z0-9_]{1,64}$/.test(err.code) ? err.code : "invalid_response",
|
|
276
|
+
ready: err.retryable ? latest.data.ready : false,
|
|
277
|
+
earlyCheckAt: err.retryable && delay !== null ? this.now() + delay : null,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
exports.ConnectionService = ConnectionService;
|
|
282
|
+
function storeFields(store) {
|
|
283
|
+
return {
|
|
284
|
+
storeId: store.storeId, displayName: store.displayName, storeStatus: store.status, sourceKind: store.sourceKind,
|
|
285
|
+
sourceCurrency: store.sourceCurrency, sourceDecimals: store.sourceDecimals, merchantDomain: store.merchantDomain,
|
|
286
|
+
paymentsReady: store.paymentsReady, paymentAssets: store.paymentAssets,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function validateStore(store, currency) {
|
|
290
|
+
if (store.status !== "active")
|
|
291
|
+
throw new ConnectionError("store_inactive");
|
|
292
|
+
if (store.sourceKind !== "fiat")
|
|
293
|
+
throw new ConnectionError("fiat_required");
|
|
294
|
+
if (store.sourceCurrency !== currency)
|
|
295
|
+
throw new ConnectionError("currency_mismatch");
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Verifies the active Secret, promoting a saved pending Secret that TLY Pay confirmed meanwhile, then
|
|
299
|
+
* a remaining pending Secret.
|
|
300
|
+
*/
|
|
301
|
+
async function verifySecrets(api, endpointId, active, pending) {
|
|
302
|
+
let result;
|
|
303
|
+
try {
|
|
304
|
+
result = await api.verifyEndpointSecret(endpointId, active);
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
if (!(error instanceof public_api_1.TlyApiError))
|
|
308
|
+
throw error;
|
|
309
|
+
if (error.code === "not_found")
|
|
310
|
+
throw ConnectionError.fromApi(error, "webhook_endpoint_mismatch");
|
|
311
|
+
if (error.code !== "webhook_secret_invalid" || pending === "")
|
|
312
|
+
throw error;
|
|
313
|
+
result = await verifyKind(api, endpointId, pending, "active");
|
|
314
|
+
active = pending;
|
|
315
|
+
pending = "";
|
|
316
|
+
}
|
|
317
|
+
checkKind(result, "active");
|
|
318
|
+
if (pending !== "")
|
|
319
|
+
await verifyKind(api, endpointId, pending, "pending");
|
|
320
|
+
return [active, pending];
|
|
321
|
+
}
|
|
322
|
+
async function verifyKind(api, endpointId, secret, kind) {
|
|
323
|
+
let result;
|
|
324
|
+
try {
|
|
325
|
+
result = await api.verifyEndpointSecret(endpointId, secret);
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
if (error instanceof public_api_1.TlyApiError) {
|
|
329
|
+
throw ConnectionError.fromApi(error, error.code === "not_found" ? "webhook_endpoint_mismatch" : undefined);
|
|
330
|
+
}
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
checkKind(result, kind);
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
function checkKind(result, kind) {
|
|
337
|
+
if (result.secretKind !== kind)
|
|
338
|
+
throw new ConnectionError("invalid_webhook_binding");
|
|
339
|
+
if (result.status !== "active")
|
|
340
|
+
throw new ConnectionError("webhook_endpoint_inactive");
|
|
341
|
+
}
|
|
342
|
+
function validateCredentials(credentials) {
|
|
343
|
+
if (!contracts_1.API_KEY.test(credentials.apiKey))
|
|
344
|
+
throw new ConnectionError("invalid_api_key");
|
|
345
|
+
if (!contracts_1.WEBHOOK_ENDPOINT_ID.test(credentials.endpointId))
|
|
346
|
+
throw new ConnectionError("invalid_webhook_endpoint_id");
|
|
347
|
+
if (!contracts_1.WEBHOOK_SECRET.test(credentials.webhookSecret)
|
|
348
|
+
|| credentials.pendingWebhookSecret !== "" && !contracts_1.WEBHOOK_SECRET.test(credentials.pendingWebhookSecret)) {
|
|
349
|
+
throw new ConnectionError("invalid_webhook_secret");
|
|
350
|
+
}
|
|
351
|
+
if (credentials.pendingWebhookSecret !== "" && credentials.pendingWebhookSecret === credentials.webhookSecret) {
|
|
352
|
+
throw new ConnectionError("duplicate_webhook_secret");
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
function toConnectionError(error) {
|
|
356
|
+
if (error instanceof ConnectionError)
|
|
357
|
+
return error;
|
|
358
|
+
if (error instanceof public_api_1.TlyApiError)
|
|
359
|
+
return ConnectionError.fromApi(error);
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export type TlyStatus = "open" | "partially_paid" | "paid" | "overpaid" | "expired" | "cancelled" | "review_required";
|
|
2
|
+
export type SourceAmount = {
|
|
3
|
+
kind: "fiat";
|
|
4
|
+
currency: string;
|
|
5
|
+
amountRaw: string;
|
|
6
|
+
decimals: number;
|
|
7
|
+
};
|
|
8
|
+
export type PaymentView = {
|
|
9
|
+
paymentId: string;
|
|
10
|
+
orderRef: string | null;
|
|
11
|
+
clientRef: string | null;
|
|
12
|
+
status: TlyStatus;
|
|
13
|
+
statusVersion: number;
|
|
14
|
+
sourceAmount: SourceAmount;
|
|
15
|
+
createdAt: string;
|
|
16
|
+
activatedAt: string | null;
|
|
17
|
+
paymentExpiresAt: string;
|
|
18
|
+
updatedAt: string;
|
|
19
|
+
};
|
|
20
|
+
/** One asset customers can pay with now, as `GET /v1/store` reports it. */
|
|
21
|
+
export type PaymentAsset = {
|
|
22
|
+
symbol: string;
|
|
23
|
+
name: string;
|
|
24
|
+
networks: string[];
|
|
25
|
+
};
|
|
26
|
+
/** The Store context of `GET /v1/store`, with only the fields this plugin relies on. */
|
|
27
|
+
export type StoreContext = {
|
|
28
|
+
storeId: string;
|
|
29
|
+
displayName: string;
|
|
30
|
+
status: string;
|
|
31
|
+
sourceKind: string;
|
|
32
|
+
sourceCurrency: string;
|
|
33
|
+
sourceDecimals: number;
|
|
34
|
+
merchantDomain: string;
|
|
35
|
+
/** The Store has a verified wallet with an enabled network; checkout stays hidden until then. */
|
|
36
|
+
paymentsReady: boolean;
|
|
37
|
+
paymentAssets: PaymentAsset[];
|
|
38
|
+
};
|
|
39
|
+
export declare const PAYMENT_ID: RegExp;
|
|
40
|
+
export declare const STORE_ID: RegExp;
|
|
41
|
+
export declare const AMOUNT_RAW: RegExp;
|
|
42
|
+
export declare const WEBHOOK_SECRET: RegExp;
|
|
43
|
+
export declare const EVENT_ID: RegExp;
|
|
44
|
+
export declare const WEBHOOK_ENDPOINT_ID: RegExp;
|
|
45
|
+
export declare const API_KEY: RegExp;
|
|
46
|
+
/** Payment statuses that end a Widget session as paid. */
|
|
47
|
+
export declare const PAID_STATUSES: readonly ["paid", "overpaid"];
|
|
48
|
+
/** This installation's Payment marker: platform code `vd` plus 20 random characters. */
|
|
49
|
+
export declare const CLIENT_REF: RegExp;
|
|
50
|
+
export declare function generateClientRef(): string;
|
|
51
|
+
export declare const TLY_STATUSES: Set<TlyStatus>;
|
|
52
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
53
|
+
/** Requires every listed field; additional fields are ignored so newer TLY Pay payloads stay accepted. */
|
|
54
|
+
export declare function hasFields(value: unknown, fields: readonly string[]): value is Record<string, unknown>;
|
|
55
|
+
/** Reads the optional `client_ref`: a missing field (older events and Payments) reads as null. */
|
|
56
|
+
export declare function optionalClientRef(value: Record<string, unknown>): string | null | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* Returns the exact `payment_assets` list of the Store Contract, or null when its shape is wrong.
|
|
59
|
+
* Every entry needs a non-empty `symbol`, a `name` and a `networks` list of strings; unknown keys
|
|
60
|
+
* are dropped. An empty list is valid and means no asset is payable yet.
|
|
61
|
+
*/
|
|
62
|
+
export declare function parsePaymentAssets(value: unknown): PaymentAsset[] | null;
|
|
63
|
+
export declare function requirePaymentId(value: unknown): string;
|
|
64
|
+
export declare function requireHttpsOrigin(value: unknown, label: string): string;
|
|
65
|
+
export declare function isRfc3339Timestamp(value: unknown): value is string;
|
|
66
|
+
export declare function validatePaymentView(value: unknown, expectedPaymentId?: string): PaymentView;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TLY_STATUSES = exports.CLIENT_REF = exports.PAID_STATUSES = exports.API_KEY = exports.WEBHOOK_ENDPOINT_ID = exports.EVENT_ID = exports.WEBHOOK_SECRET = exports.AMOUNT_RAW = exports.STORE_ID = exports.PAYMENT_ID = void 0;
|
|
4
|
+
exports.generateClientRef = generateClientRef;
|
|
5
|
+
exports.isRecord = isRecord;
|
|
6
|
+
exports.hasFields = hasFields;
|
|
7
|
+
exports.optionalClientRef = optionalClientRef;
|
|
8
|
+
exports.parsePaymentAssets = parsePaymentAssets;
|
|
9
|
+
exports.requirePaymentId = requirePaymentId;
|
|
10
|
+
exports.requireHttpsOrigin = requireHttpsOrigin;
|
|
11
|
+
exports.isRfc3339Timestamp = isRfc3339Timestamp;
|
|
12
|
+
exports.validatePaymentView = validatePaymentView;
|
|
13
|
+
const node_crypto_1 = require("node:crypto");
|
|
14
|
+
const node_net_1 = require("node:net");
|
|
15
|
+
exports.PAYMENT_ID = /^c[a-z0-9]{20}o$/;
|
|
16
|
+
exports.STORE_ID = /^s[a-z0-9]{16}t$/;
|
|
17
|
+
exports.AMOUNT_RAW = /^[1-9][0-9]{0,77}$/;
|
|
18
|
+
exports.WEBHOOK_SECRET = /^whsec_[A-Za-z0-9_-]{26,250}$/;
|
|
19
|
+
exports.EVENT_ID = /^e[a-z0-9]{20}v$/;
|
|
20
|
+
exports.WEBHOOK_ENDPOINT_ID = /^w[0-9a-z]{16}e$/;
|
|
21
|
+
exports.API_KEY = /^[\x21-\x7e]{1,255}$/;
|
|
22
|
+
/** Payment statuses that end a Widget session as paid. */
|
|
23
|
+
exports.PAID_STATUSES = ["paid", "overpaid"];
|
|
24
|
+
/** This installation's Payment marker: platform code `vd` plus 20 random characters. */
|
|
25
|
+
exports.CLIENT_REF = /^vd_[0-9a-z]{20}$/;
|
|
26
|
+
const CLIENT_REF_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
27
|
+
function generateClientRef() {
|
|
28
|
+
let suffix = "";
|
|
29
|
+
for (let index = 0; index < 20; index++)
|
|
30
|
+
suffix += CLIENT_REF_ALPHABET[(0, node_crypto_1.randomInt)(CLIENT_REF_ALPHABET.length)];
|
|
31
|
+
return `vd_${suffix}`;
|
|
32
|
+
}
|
|
33
|
+
exports.TLY_STATUSES = new Set([
|
|
34
|
+
"open", "partially_paid", "paid", "overpaid", "expired", "cancelled", "review_required",
|
|
35
|
+
]);
|
|
36
|
+
function isRecord(value) {
|
|
37
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
38
|
+
}
|
|
39
|
+
/** Requires every listed field; additional fields are ignored so newer TLY Pay payloads stay accepted. */
|
|
40
|
+
function hasFields(value, fields) {
|
|
41
|
+
return isRecord(value) && fields.every((field) => Object.hasOwn(value, field));
|
|
42
|
+
}
|
|
43
|
+
/** Reads the optional `client_ref`: a missing field (older events and Payments) reads as null. */
|
|
44
|
+
function optionalClientRef(value) {
|
|
45
|
+
if (!Object.hasOwn(value, "client_ref") || value.client_ref === null)
|
|
46
|
+
return null;
|
|
47
|
+
return typeof value.client_ref === "string" ? value.client_ref : undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Returns the exact `payment_assets` list of the Store Contract, or null when its shape is wrong.
|
|
51
|
+
* Every entry needs a non-empty `symbol`, a `name` and a `networks` list of strings; unknown keys
|
|
52
|
+
* are dropped. An empty list is valid and means no asset is payable yet.
|
|
53
|
+
*/
|
|
54
|
+
function parsePaymentAssets(value) {
|
|
55
|
+
if (!Array.isArray(value))
|
|
56
|
+
return null;
|
|
57
|
+
const assets = [];
|
|
58
|
+
for (const asset of value) {
|
|
59
|
+
if (!isRecord(asset) || typeof asset.symbol !== "string" || asset.symbol === ""
|
|
60
|
+
|| typeof asset.name !== "string" || !Array.isArray(asset.networks)
|
|
61
|
+
|| asset.networks.some((network) => typeof network !== "string")) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
assets.push({ symbol: asset.symbol, name: asset.name, networks: [...asset.networks] });
|
|
65
|
+
}
|
|
66
|
+
return assets;
|
|
67
|
+
}
|
|
68
|
+
function requirePaymentId(value) {
|
|
69
|
+
if (typeof value !== "string" || !exports.PAYMENT_ID.test(value)) {
|
|
70
|
+
throw new TypeError("Invalid TLY Pay Payment ID");
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function requireHttpsOrigin(value, label) {
|
|
75
|
+
if (typeof value !== "string")
|
|
76
|
+
throw new TypeError(`${label} must be an HTTPS Origin`);
|
|
77
|
+
let parsed;
|
|
78
|
+
try {
|
|
79
|
+
parsed = new URL(value);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new TypeError(`${label} must be an HTTPS Origin`);
|
|
83
|
+
}
|
|
84
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.port
|
|
85
|
+
|| parsed.pathname !== "/" || parsed.search || parsed.hash
|
|
86
|
+
|| !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(parsed.hostname)
|
|
87
|
+
|| (0, node_net_1.isIP)(parsed.hostname) !== 0) {
|
|
88
|
+
throw new TypeError(`${label} must be an HTTPS Origin`);
|
|
89
|
+
}
|
|
90
|
+
return parsed.origin;
|
|
91
|
+
}
|
|
92
|
+
function isRfc3339Timestamp(value) {
|
|
93
|
+
if (typeof value !== "string")
|
|
94
|
+
return false;
|
|
95
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(value);
|
|
96
|
+
if (match === null)
|
|
97
|
+
return false;
|
|
98
|
+
const year = Number(match[1]);
|
|
99
|
+
const month = Number(match[2]);
|
|
100
|
+
const day = Number(match[3]);
|
|
101
|
+
const hour = Number(match[4]);
|
|
102
|
+
const minute = Number(match[5]);
|
|
103
|
+
const second = Number(match[6]);
|
|
104
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
105
|
+
const monthDays = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
106
|
+
const maxDay = monthDays[month - 1] ?? 0;
|
|
107
|
+
return year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= maxDay
|
|
108
|
+
&& hour <= 23 && minute <= 59 && second <= 59
|
|
109
|
+
&& (match[7] === undefined || Number(match[7]) <= 23 && Number(match[8]) <= 59);
|
|
110
|
+
}
|
|
111
|
+
function validatePaymentView(value, expectedPaymentId) {
|
|
112
|
+
const clientRef = isRecord(value) ? optionalClientRef(value) : undefined;
|
|
113
|
+
if (!hasFields(value, [
|
|
114
|
+
"payment_id", "order_ref", "status", "status_version", "source_amount",
|
|
115
|
+
"created_at", "activated_at", "payment_expires_at", "updated_at",
|
|
116
|
+
]) || typeof value.payment_id !== "string" || !exports.PAYMENT_ID.test(value.payment_id)
|
|
117
|
+
|| expectedPaymentId !== undefined && value.payment_id !== expectedPaymentId
|
|
118
|
+
|| value.order_ref !== null && typeof value.order_ref !== "string"
|
|
119
|
+
|| clientRef === undefined
|
|
120
|
+
|| typeof value.status !== "string" || !exports.TLY_STATUSES.has(value.status)
|
|
121
|
+
|| !Number.isSafeInteger(value.status_version) || value.status_version < 1
|
|
122
|
+
|| !hasFields(value.source_amount, ["kind", "currency", "amount_raw", "decimals"])
|
|
123
|
+
|| value.source_amount.kind !== "fiat"
|
|
124
|
+
|| typeof value.source_amount.currency !== "string" || !/^[A-Z]{3}$/.test(value.source_amount.currency)
|
|
125
|
+
|| typeof value.source_amount.amount_raw !== "string" || !exports.AMOUNT_RAW.test(value.source_amount.amount_raw)
|
|
126
|
+
|| !Number.isInteger(value.source_amount.decimals) || value.source_amount.decimals < 0
|
|
127
|
+
|| value.source_amount.decimals > 18
|
|
128
|
+
|| !isRfc3339Timestamp(value.created_at)
|
|
129
|
+
|| value.activated_at !== null && !isRfc3339Timestamp(value.activated_at)
|
|
130
|
+
|| !isRfc3339Timestamp(value.payment_expires_at)
|
|
131
|
+
|| !isRfc3339Timestamp(value.updated_at)) {
|
|
132
|
+
throw new TypeError("Invalid authoritative Payment response");
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
paymentId: value.payment_id,
|
|
136
|
+
orderRef: value.order_ref,
|
|
137
|
+
clientRef,
|
|
138
|
+
status: value.status,
|
|
139
|
+
statusVersion: value.status_version,
|
|
140
|
+
sourceAmount: {
|
|
141
|
+
kind: "fiat",
|
|
142
|
+
currency: value.source_amount.currency,
|
|
143
|
+
amountRaw: value.source_amount.amount_raw,
|
|
144
|
+
decimals: value.source_amount.decimals,
|
|
145
|
+
},
|
|
146
|
+
createdAt: value.created_at,
|
|
147
|
+
activatedAt: value.activated_at,
|
|
148
|
+
paymentExpiresAt: value.payment_expires_at,
|
|
149
|
+
updatedAt: value.updated_at,
|
|
150
|
+
};
|
|
151
|
+
}
|