@paymos/mcp 1.5.0 → 1.6.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 +11 -0
- package/README.md +62 -7
- package/dist/index.js +1755 -607
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import { realpathSync } from "fs";
|
|
4
|
+
import { realpathSync as realpathSync3 } from "fs";
|
|
5
5
|
import { pathToFileURL } from "url";
|
|
6
6
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
7
|
|
|
8
|
+
// src/auth.ts
|
|
9
|
+
import { spawn } from "child_process";
|
|
10
|
+
import { accessSync, constants as constants3, lstatSync as lstatSync4, realpathSync } from "fs";
|
|
11
|
+
import { homedir as homedir2 } from "os";
|
|
12
|
+
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join2, parse, relative, resolve as resolve2, sep } from "path";
|
|
13
|
+
|
|
14
|
+
// src/setup.ts
|
|
15
|
+
import {
|
|
16
|
+
chmodSync,
|
|
17
|
+
closeSync as closeSync3,
|
|
18
|
+
constants as constants2,
|
|
19
|
+
existsSync,
|
|
20
|
+
fstatSync as fstatSync3,
|
|
21
|
+
linkSync,
|
|
22
|
+
lstatSync as lstatSync3,
|
|
23
|
+
mkdirSync as mkdirSync2,
|
|
24
|
+
openSync as openSync3,
|
|
25
|
+
readFileSync as readFileSync2,
|
|
26
|
+
renameSync,
|
|
27
|
+
unlinkSync as unlinkSync2,
|
|
28
|
+
writeFileSync
|
|
29
|
+
} from "fs";
|
|
30
|
+
import { randomUUID } from "crypto";
|
|
31
|
+
import { homedir } from "os";
|
|
32
|
+
import { dirname as dirname2, isAbsolute, join, resolve } from "path";
|
|
33
|
+
import { createInterface } from "readline";
|
|
34
|
+
import { Writable } from "stream";
|
|
35
|
+
import { isDeepStrictEqual } from "util";
|
|
36
|
+
import { applyEdits, modify, parse as parseJson, parseTree } from "jsonc-parser";
|
|
37
|
+
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
|
38
|
+
|
|
8
39
|
// src/credential-file.ts
|
|
9
40
|
import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync } from "fs";
|
|
10
41
|
|
|
@@ -62,6 +93,20 @@ Restart or reconnect your MCP client after setup.`,
|
|
|
62
93
|
write: "Setup could not save the files. Check the target paths and write permissions, then retry."
|
|
63
94
|
}
|
|
64
95
|
};
|
|
96
|
+
var AUTH_COPY = {
|
|
97
|
+
help: "Usage: paymos auth [--client codex|claude-code]\n\nConnect your merchant account in the client's browser sign-in.",
|
|
98
|
+
chooseClient: "Choose your MCP client (codex or claude-code)",
|
|
99
|
+
errors: {
|
|
100
|
+
client_required: "Choose your client with --client codex or --client claude-code.",
|
|
101
|
+
configuration_conflict: "A Paymos entry conflicts with this connection or changed during setup. Review your MCP settings and try again.",
|
|
102
|
+
configuration_scope_unknown: "The effective MCP configuration could not be verified. Use Authenticate in your client's MCP settings.",
|
|
103
|
+
client_installation_unknown: "A supported client installation could not be verified. Use Authenticate in your client's MCP settings or run its native mcp login command.",
|
|
104
|
+
auth_cancelled: "Sign-in was cancelled.",
|
|
105
|
+
auth_failed: "The client could not complete sign-in. Check its output for details.",
|
|
106
|
+
configuration_restore_skipped: "Could not restore the previous MCP settings. Review your client's configuration before retrying.",
|
|
107
|
+
configuration_write_failed: "Could not save the MCP settings. Check the file and its permissions."
|
|
108
|
+
}
|
|
109
|
+
};
|
|
65
110
|
|
|
66
111
|
// src/credential-file.ts
|
|
67
112
|
function readCredentialFile(path) {
|
|
@@ -70,9 +115,9 @@ function readCredentialFile(path) {
|
|
|
70
115
|
const link = lstatSync(path);
|
|
71
116
|
if (!link.isFile() || link.isSymbolicLink()) throw new Error();
|
|
72
117
|
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
73
|
-
const
|
|
74
|
-
if (!
|
|
75
|
-
if (process.platform !== "win32" && ((
|
|
118
|
+
const stat2 = fstatSync(fd);
|
|
119
|
+
if (!stat2.isFile() || stat2.size > 16384 || stat2.ino !== link.ino) throw new Error();
|
|
120
|
+
if (process.platform !== "win32" && ((stat2.mode & 63) !== 0 || process.getuid !== void 0 && stat2.uid !== process.getuid())) throw new Error();
|
|
76
121
|
const value = JSON.parse(readFileSync(fd, "utf8"));
|
|
77
122
|
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error();
|
|
78
123
|
const record = value;
|
|
@@ -89,38 +134,6 @@ function readCredentialFile(path) {
|
|
|
89
134
|
}
|
|
90
135
|
}
|
|
91
136
|
|
|
92
|
-
// src/config.ts
|
|
93
|
-
var FLAG_NAMES = /* @__PURE__ */ new Map([
|
|
94
|
-
["--api-key-id", "apiKeyId"],
|
|
95
|
-
["--api-secret", "apiSecret"]
|
|
96
|
-
]);
|
|
97
|
-
function parseFlags(argv) {
|
|
98
|
-
const flags = {};
|
|
99
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
100
|
-
const token = argv[index];
|
|
101
|
-
if (token === void 0 || token === "--") break;
|
|
102
|
-
const equals = token.indexOf("=");
|
|
103
|
-
const head = equals < 0 ? token : token.slice(0, equals);
|
|
104
|
-
const field = FLAG_NAMES.get(head);
|
|
105
|
-
if (!field) continue;
|
|
106
|
-
const value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
|
|
107
|
-
if (value === void 0) break;
|
|
108
|
-
flags[field] = value;
|
|
109
|
-
if (equals < 0) index += 1;
|
|
110
|
-
}
|
|
111
|
-
return flags;
|
|
112
|
-
}
|
|
113
|
-
function loadCredentials(env, flags) {
|
|
114
|
-
const file = env.PAYMOS_CREDENTIALS_FILE === void 0 ? void 0 : readCredentialFile(env.PAYMOS_CREDENTIALS_FILE);
|
|
115
|
-
const apiKeyId = (env.PAYMOS_API_KEY_ID ?? flags.apiKeyId ?? file?.apiKeyId ?? "").trim();
|
|
116
|
-
const apiSecret = (env.PAYMOS_API_SECRET ?? flags.apiSecret ?? file?.apiSecret ?? "").trim();
|
|
117
|
-
const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? file?.webhookSecret ?? "").trim();
|
|
118
|
-
return webhookSecret === "" ? { apiKeyId, apiSecret } : { apiKeyId, apiSecret, webhookSecret };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// src/gateway.ts
|
|
122
|
-
import { Paymos } from "@paymos/sdk";
|
|
123
|
-
|
|
124
137
|
// src/gate.ts
|
|
125
138
|
var SANDBOX_ONLY_CODE = "paymos/sandbox-only";
|
|
126
139
|
var SANDBOX_ONLY_MESSAGE = "Live keys arrive in phase 2. Create a test key pair in Dashboard \u2192 Developers \u2192 API keys.";
|
|
@@ -148,166 +161,1600 @@ function checkCredentials(credentials) {
|
|
|
148
161
|
function startupLine(check, apiKeyId) {
|
|
149
162
|
return check.ok ? `[paymos-mcp] sandbox session ready (${apiKeyId.slice(0, TEST_KEY_PREFIX.length + 4)}\u2026)` : `[paymos-mcp] ${check.code}: ${check.message}`;
|
|
150
163
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
164
|
+
var deliveryMessages = {
|
|
165
|
+
delivery_arguments: "Check the required --prepare or --token, --request-id, and file options.",
|
|
166
|
+
delivery_unsafe_path: "Choose a regular file inside the current directory, without links or traversal.",
|
|
167
|
+
delivery_state_unavailable: "The local delivery preparation is missing, expired, or already used.",
|
|
168
|
+
delivery_context_mismatch: "The delivery does not match its prepared operation or file.",
|
|
169
|
+
delivery_unavailable: "The delivery is unavailable from its original connection.",
|
|
170
|
+
delivery_request_failed: "Paymos could not complete the delivery request.",
|
|
171
|
+
delivery_invalid_response: "Paymos returned an unexpected delivery response.",
|
|
172
|
+
delivery_file_too_large: "The delivery exceeds the file size limit.",
|
|
173
|
+
delivery_local_io_failed: "The delivery could not be saved locally."
|
|
174
|
+
};
|
|
175
|
+
var MerchantDeliveryError = class extends Error {
|
|
176
|
+
constructor(code) {
|
|
177
|
+
super(code + ": " + deliveryMessages[code]);
|
|
159
178
|
this.code = code;
|
|
160
179
|
}
|
|
161
180
|
};
|
|
162
|
-
function toolErrorFrom(error2) {
|
|
163
|
-
if (error2 instanceof ToolError) return error2;
|
|
164
|
-
if (error2 instanceof ApiError) {
|
|
165
|
-
const code = error2.code === "" ? "api_error" : error2.code;
|
|
166
|
-
return new ToolError(`paymos/${code}`, error2.message);
|
|
167
|
-
}
|
|
168
|
-
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
169
|
-
return new ToolError("paymos/sdk_error", message);
|
|
170
|
-
}
|
|
171
181
|
|
|
172
|
-
// src/
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return checkCredentials(this.credentials);
|
|
182
|
-
}
|
|
183
|
-
/** Webhook signing secret for the local `verify_webhook_signature` tool. */
|
|
184
|
-
webhookSecret() {
|
|
185
|
-
return this.credentials.webhookSecret;
|
|
186
|
-
}
|
|
187
|
-
client() {
|
|
188
|
-
const check = this.check();
|
|
189
|
-
if (!check.ok) throw new ToolError(check.code, check.message);
|
|
190
|
-
return new Paymos({
|
|
191
|
-
apiKey: this.credentials.apiKeyId,
|
|
192
|
-
apiSecret: this.credentials.apiSecret,
|
|
193
|
-
...this.overrides.fetch ? { fetch: this.overrides.fetch } : {}
|
|
194
|
-
});
|
|
182
|
+
// src/setup-lock.ts
|
|
183
|
+
import { closeSync as closeSync2, fstatSync as fstatSync2, lstatSync as lstatSync2, mkdirSync, openSync as openSync2, unlinkSync } from "fs";
|
|
184
|
+
import { dirname } from "path";
|
|
185
|
+
var LOCK_SUFFIX = ".paymos-setup.lock";
|
|
186
|
+
var STALE_LOCK_MS = 3e4;
|
|
187
|
+
var DestinationBusyError = class extends Error {
|
|
188
|
+
constructor() {
|
|
189
|
+
super("Another setup is publishing to this destination.");
|
|
190
|
+
this.name = "DestinationBusyError";
|
|
195
191
|
}
|
|
196
|
-
|
|
197
|
-
|
|
192
|
+
};
|
|
193
|
+
function sameIdentity(first, second) {
|
|
194
|
+
return first.ino === second.ino && first.dev === second.dev && first.birthtimeNs === second.birthtimeNs;
|
|
195
|
+
}
|
|
196
|
+
function acquire(lock, now) {
|
|
197
|
+
for (let attempt = 0; ; attempt++) {
|
|
198
|
+
let fd;
|
|
199
|
+
try {
|
|
200
|
+
fd = openSync2(lock, "wx", 384);
|
|
201
|
+
} catch (cause) {
|
|
202
|
+
if (cause.code !== "EEXIST") throw cause;
|
|
203
|
+
if (attempt > 0 || !removeIfStale(lock, now)) throw new DestinationBusyError();
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const opened = fstatSync2(fd, { bigint: true });
|
|
208
|
+
const pathStat2 = lstatSync2(lock, { bigint: true });
|
|
209
|
+
if (!opened.isFile() || !pathStat2.isFile() || opened.ino !== pathStat2.ino || opened.birthtimeNs !== pathStat2.birthtimeNs || opened.dev !== 0n && pathStat2.dev !== 0n && opened.dev !== pathStat2.dev) {
|
|
210
|
+
throw new DestinationBusyError();
|
|
211
|
+
}
|
|
212
|
+
return pathStat2;
|
|
213
|
+
} finally {
|
|
214
|
+
closeSync2(fd);
|
|
215
|
+
}
|
|
198
216
|
}
|
|
199
|
-
|
|
200
|
-
|
|
217
|
+
}
|
|
218
|
+
function removeIfStale(lock, now) {
|
|
219
|
+
try {
|
|
220
|
+
const stale = lstatSync2(lock, { bigint: true });
|
|
221
|
+
if (!stale.isFile() || now() - Number(stale.mtimeMs) < STALE_LOCK_MS) return false;
|
|
222
|
+
const current = lstatSync2(lock, { bigint: true });
|
|
223
|
+
if (!current.isFile() || !sameIdentity(stale, current) || stale.mtimeNs !== current.mtimeNs) return false;
|
|
224
|
+
unlinkSync(lock);
|
|
225
|
+
return true;
|
|
226
|
+
} catch (cause) {
|
|
227
|
+
return cause.code === "ENOENT";
|
|
201
228
|
}
|
|
202
|
-
|
|
203
|
-
|
|
229
|
+
}
|
|
230
|
+
function release(lock, mine) {
|
|
231
|
+
try {
|
|
232
|
+
const stat2 = lstatSync2(lock, { bigint: true });
|
|
233
|
+
if (stat2.isFile() && sameIdentity(stat2, mine)) unlinkSync(lock);
|
|
234
|
+
} catch {
|
|
204
235
|
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
// src/wire-shape.ts
|
|
215
|
-
function toWireShape(value) {
|
|
216
|
-
if (Array.isArray(value)) return value.map(toWireShape);
|
|
217
|
-
if (value === null || typeof value !== "object") return value;
|
|
218
|
-
const out = {};
|
|
219
|
-
for (const [key, item] of Object.entries(value)) {
|
|
220
|
-
out[key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)] = toWireShape(item);
|
|
236
|
+
}
|
|
237
|
+
function withDestinationLock(destination, action, now = Date.now) {
|
|
238
|
+
const lock = destination + LOCK_SUFFIX;
|
|
239
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 448 });
|
|
240
|
+
const mine = acquire(lock, now);
|
|
241
|
+
try {
|
|
242
|
+
return action();
|
|
243
|
+
} finally {
|
|
244
|
+
release(lock, mine);
|
|
221
245
|
}
|
|
222
|
-
return out;
|
|
223
246
|
}
|
|
224
247
|
|
|
225
|
-
// src/
|
|
226
|
-
var
|
|
227
|
-
|
|
228
|
-
"
|
|
229
|
-
"
|
|
230
|
-
"
|
|
231
|
-
"
|
|
232
|
-
"
|
|
233
|
-
"
|
|
234
|
-
"
|
|
235
|
-
"
|
|
236
|
-
"cancelled"
|
|
248
|
+
// src/setup.ts
|
|
249
|
+
var SETUP_CLIENTS = [
|
|
250
|
+
"codex",
|
|
251
|
+
"claude-code",
|
|
252
|
+
"claude-desktop",
|
|
253
|
+
"kimi",
|
|
254
|
+
"cursor",
|
|
255
|
+
"windsurf",
|
|
256
|
+
"opencode",
|
|
257
|
+
"vscode",
|
|
258
|
+
"generic"
|
|
237
259
|
];
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
return {
|
|
241
|
-
content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
|
|
242
|
-
};
|
|
260
|
+
function error(kind) {
|
|
261
|
+
throw new Error(SETUP_COPY.errors[kind]);
|
|
243
262
|
}
|
|
244
|
-
function
|
|
245
|
-
|
|
246
|
-
return {
|
|
247
|
-
isError: true,
|
|
248
|
-
content: [{ type: "text", text: JSON.stringify({ code: toolError.code, message: toolError.message }, null, 2) }]
|
|
249
|
-
};
|
|
263
|
+
function sameIdentity2(a, b) {
|
|
264
|
+
return a.ino === b.ino && a.dev === b.dev && a.birthtimeNs === b.birthtimeNs;
|
|
250
265
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
266
|
+
function options(argv) {
|
|
267
|
+
const result = { dryRun: false, help: false };
|
|
268
|
+
const seen = /* @__PURE__ */ new Set();
|
|
269
|
+
const flags = /* @__PURE__ */ new Map([
|
|
270
|
+
["--client", "client"],
|
|
271
|
+
["--config", "config"],
|
|
272
|
+
["--credentials-file", "credentialsFile"]
|
|
273
|
+
]);
|
|
274
|
+
for (let i = 0; i < argv.length; i++) {
|
|
275
|
+
const arg = argv[i];
|
|
276
|
+
const split = arg.indexOf("=");
|
|
277
|
+
const flag = split < 0 ? arg : arg.slice(0, split);
|
|
278
|
+
const normalized = flag === "-h" ? "--help" : flag;
|
|
279
|
+
if (seen.has(normalized)) error("arguments");
|
|
280
|
+
seen.add(normalized);
|
|
281
|
+
if (normalized === "--help" || normalized === "--dry-run") {
|
|
282
|
+
if (split >= 0) error("arguments");
|
|
283
|
+
if (normalized === "--help") result.help = true;
|
|
284
|
+
else result.dryRun = true;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const field = flags.get(flag);
|
|
288
|
+
if (!field) error("arguments");
|
|
289
|
+
const value = split < 0 ? argv[++i] : arg.slice(split + 1);
|
|
290
|
+
if (value === void 0 || value.trim() === "" || value.startsWith("--")) error("arguments");
|
|
291
|
+
result[field] = value;
|
|
256
292
|
}
|
|
293
|
+
return result;
|
|
257
294
|
}
|
|
258
|
-
function
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
"
|
|
309
|
-
|
|
310
|
-
|
|
295
|
+
function object(value) {
|
|
296
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
297
|
+
}
|
|
298
|
+
function equalData(left, right) {
|
|
299
|
+
if (isDeepStrictEqual(left, right)) return true;
|
|
300
|
+
if (!object(left) || !object(right)) return false;
|
|
301
|
+
const plain = (value) => Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype;
|
|
302
|
+
if (!plain(left) || !plain(right)) return false;
|
|
303
|
+
const keys = Object.keys(left);
|
|
304
|
+
return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalData(left[key], right[key]));
|
|
305
|
+
}
|
|
306
|
+
function absolute(path, context) {
|
|
307
|
+
if (path === "~") return context.home;
|
|
308
|
+
if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(context.home, path.slice(2));
|
|
309
|
+
return resolve(context.cwd, path);
|
|
310
|
+
}
|
|
311
|
+
function defaultConfigPath(client, env, context) {
|
|
312
|
+
const configHome = env.XDG_CONFIG_HOME || join(context.home, ".config");
|
|
313
|
+
switch (client) {
|
|
314
|
+
case "codex":
|
|
315
|
+
return join(env.CODEX_HOME || join(context.home, ".codex"), "config.toml");
|
|
316
|
+
case "claude-code":
|
|
317
|
+
return join(context.home, ".claude.json");
|
|
318
|
+
case "kimi":
|
|
319
|
+
return join(env.KIMI_CODE_HOME || join(context.home, ".kimi-code"), "mcp.json");
|
|
320
|
+
case "cursor":
|
|
321
|
+
return join(context.home, ".cursor", "mcp.json");
|
|
322
|
+
case "windsurf":
|
|
323
|
+
return join(context.home, ".codeium", "windsurf", "mcp_config.json");
|
|
324
|
+
case "vscode":
|
|
325
|
+
return join(context.cwd, ".vscode", "mcp.json");
|
|
326
|
+
case "opencode": {
|
|
327
|
+
if (env.OPENCODE_CONFIG) return env.OPENCODE_CONFIG;
|
|
328
|
+
const jsonc = join(configHome, "opencode", "opencode.jsonc");
|
|
329
|
+
return existsSync(jsonc) ? jsonc : join(configHome, "opencode", "opencode.json");
|
|
330
|
+
}
|
|
331
|
+
case "claude-desktop":
|
|
332
|
+
if (context.platform === "win32" && env.APPDATA)
|
|
333
|
+
return join(env.APPDATA, "Claude", "claude_desktop_config.json");
|
|
334
|
+
if (context.platform === "darwin")
|
|
335
|
+
return join(context.home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
336
|
+
return error("configRequired");
|
|
337
|
+
case "generic":
|
|
338
|
+
return error("configRequired");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function snapshot(path) {
|
|
342
|
+
let fd;
|
|
343
|
+
try {
|
|
344
|
+
const stat2 = lstatSync3(path, { bigint: true });
|
|
345
|
+
if (stat2.isSymbolicLink()) error("symlink");
|
|
346
|
+
if (!stat2.isFile() || stat2.size > 4194304n) error("configFile");
|
|
347
|
+
fd = openSync3(path, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
|
|
348
|
+
const opened = fstatSync3(fd, { bigint: true });
|
|
349
|
+
if (opened.ino !== stat2.ino || opened.birthtimeNs !== stat2.birthtimeNs || stat2.dev !== 0n && opened.dev !== stat2.dev) error("changed");
|
|
350
|
+
return { path, content: readFileSync2(fd, "utf8"), identity: stat2 };
|
|
351
|
+
} catch (cause) {
|
|
352
|
+
if (cause.code === "ENOENT") return { path, content: null };
|
|
353
|
+
if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
|
|
354
|
+
return error("configFile");
|
|
355
|
+
} finally {
|
|
356
|
+
if (fd !== void 0) closeSync3(fd);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
function assertUnchanged(before) {
|
|
360
|
+
const current = snapshot(before.path);
|
|
361
|
+
if (current.content !== before.content || current.content !== null && before.content !== null && !sameIdentity2(current.identity, before.identity)) error("changed");
|
|
362
|
+
}
|
|
363
|
+
function assertUniqueKeys(node) {
|
|
364
|
+
if (node.type === "object") {
|
|
365
|
+
const keys = /* @__PURE__ */ new Set();
|
|
366
|
+
for (const property of node.children ?? []) {
|
|
367
|
+
const key = property.children?.[0]?.value;
|
|
368
|
+
if (keys.has(key)) error("configFile");
|
|
369
|
+
keys.add(key);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
for (const child of node.children ?? []) assertUniqueKeys(child);
|
|
373
|
+
}
|
|
374
|
+
function jsonConfig(text) {
|
|
375
|
+
const errors = [];
|
|
376
|
+
const value = parseJson(text, errors, { allowTrailingComma: true, allowEmptyContent: false });
|
|
377
|
+
const tree = parseTree(text, [], { allowTrailingComma: true });
|
|
378
|
+
if (errors.length !== 0 || !object(value) || !tree) error("configFile");
|
|
379
|
+
assertUniqueKeys(tree);
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
function parseConfig(format, original) {
|
|
383
|
+
if (format === "jsonc") return jsonConfig(original ?? "{}\n");
|
|
384
|
+
try {
|
|
385
|
+
return parseToml(original ?? "");
|
|
386
|
+
} catch {
|
|
387
|
+
return error("configFile");
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function configEntries(root, group) {
|
|
391
|
+
const entries = root[group];
|
|
392
|
+
if (entries === void 0) return {};
|
|
393
|
+
if (!object(entries)) return error("configFile");
|
|
394
|
+
return entries;
|
|
395
|
+
}
|
|
396
|
+
function planConfigEntry(format, original, group, name, entry) {
|
|
397
|
+
const root = parseConfig(format, original);
|
|
398
|
+
const entries = configEntries(root, group);
|
|
399
|
+
if (Object.hasOwn(entries, name)) {
|
|
400
|
+
if (!equalData(entries[name], entry)) error("conflict");
|
|
401
|
+
return original;
|
|
402
|
+
}
|
|
403
|
+
const text = original ?? (format === "toml" ? "" : "{}\n");
|
|
404
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
405
|
+
const next = format === "toml" ? text + eol + stringifyToml({ [group]: { [name]: entry } }).replace(/\r?\n/g, eol) : applyEdits(text, modify(text, [group, name], entry, {
|
|
406
|
+
formattingOptions: { insertSpaces: true, tabSize: 2, eol }
|
|
407
|
+
}));
|
|
408
|
+
const expected = { ...root, [group]: { ...entries, [name]: entry } };
|
|
409
|
+
if (!equalData(parseConfig(format, next), expected)) error("configFile");
|
|
410
|
+
return next;
|
|
411
|
+
}
|
|
412
|
+
function planClientConfig(client, original, credentialsPath, platform) {
|
|
413
|
+
const command = platform === "win32" ? "cmd" : "npx";
|
|
414
|
+
const args = platform === "win32" ? ["/d", "/c", "npx", "-y", "@paymos/mcp"] : ["-y", "@paymos/mcp"];
|
|
415
|
+
const env = { PAYMOS_CREDENTIALS_FILE: credentialsPath };
|
|
416
|
+
const entry = client === "opencode" ? { type: "local", command: [command, ...args], environment: env, enabled: true } : { ...client === "vscode" ? { type: "stdio" } : {}, command, args, env };
|
|
417
|
+
if (client === "codex") return planConfigEntry("toml", original, "mcp_servers", "paymos", entry);
|
|
418
|
+
const group = client === "opencode" ? "mcp" : client === "vscode" ? "servers" : "mcpServers";
|
|
419
|
+
return planConfigEntry("jsonc", original, group, "paymos", entry);
|
|
420
|
+
}
|
|
421
|
+
function writeConfig(before, content) {
|
|
422
|
+
mkdirSync2(dirname2(before.path), { recursive: true, mode: 448 });
|
|
423
|
+
const temp = join(dirname2(before.path), `.paymos-${randomUUID()}.tmp`);
|
|
424
|
+
let created = false;
|
|
425
|
+
try {
|
|
426
|
+
writeFileSync(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
427
|
+
created = true;
|
|
428
|
+
if (process.platform !== "win32") chmodSync(temp, 384);
|
|
429
|
+
const identity = lstatSync3(temp, { bigint: true });
|
|
430
|
+
assertUnchanged(before);
|
|
431
|
+
if (before.content === null) linkSync(temp, before.path);
|
|
432
|
+
else renameSync(temp, before.path);
|
|
433
|
+
return identity;
|
|
434
|
+
} finally {
|
|
435
|
+
if (created && existsSync(temp)) unlinkSync2(temp);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
function restoreConfig(before, content, identity) {
|
|
439
|
+
const current = snapshot(before.path);
|
|
440
|
+
if (current.content === null || current.content !== content || !sameIdentity2(current.identity, identity)) return false;
|
|
441
|
+
if (before.content === null) unlinkSync2(before.path);
|
|
442
|
+
else writeConfig(current, before.content);
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
async function ask(io, label, secret = false) {
|
|
446
|
+
if (!io.interactive) error("nonInteractive");
|
|
447
|
+
return (await io.ask(label, secret)).trim();
|
|
448
|
+
}
|
|
449
|
+
function terminalIO() {
|
|
450
|
+
return {
|
|
451
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
452
|
+
log: (message) => console.log(message),
|
|
453
|
+
ask: (label, secret) => new Promise((accept, reject) => {
|
|
454
|
+
let muted = false;
|
|
455
|
+
const output = new Writable({ write(chunk, _encoding, done) {
|
|
456
|
+
if (!muted) process.stdout.write(chunk);
|
|
457
|
+
done();
|
|
458
|
+
} });
|
|
459
|
+
const reader = createInterface({ input: process.stdin, output, terminal: true });
|
|
460
|
+
let settled = false;
|
|
461
|
+
const cancel = () => {
|
|
462
|
+
if (settled) return;
|
|
463
|
+
settled = true;
|
|
464
|
+
muted = false;
|
|
465
|
+
process.stdout.write("\n");
|
|
466
|
+
reader.close();
|
|
467
|
+
reject(new Error(SETUP_COPY.errors.cancelled));
|
|
468
|
+
};
|
|
469
|
+
reader.once("SIGINT", cancel);
|
|
470
|
+
reader.once("close", () => {
|
|
471
|
+
if (!settled) cancel();
|
|
472
|
+
});
|
|
473
|
+
process.stdout.write(`${label}: `);
|
|
474
|
+
muted = secret;
|
|
475
|
+
reader.question("", (answer) => {
|
|
476
|
+
settled = true;
|
|
477
|
+
muted = false;
|
|
478
|
+
if (secret) process.stdout.write("\n");
|
|
479
|
+
reader.close();
|
|
480
|
+
accept(answer);
|
|
481
|
+
});
|
|
482
|
+
})
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
async function runSetup(argv, env = process.env, io = terminalIO(), context = { home: homedir(), cwd: process.cwd(), platform: process.platform }) {
|
|
486
|
+
const flags = options(argv);
|
|
487
|
+
if (flags.help) {
|
|
488
|
+
io.log(SETUP_COPY.help);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
io.log(SETUP_COPY.title);
|
|
492
|
+
const requested = flags.client ?? await ask(io, `${SETUP_COPY.chooseClient} (${SETUP_CLIENTS.join(", ")})`);
|
|
493
|
+
if (!SETUP_CLIENTS.includes(requested)) error("client");
|
|
494
|
+
const client = requested;
|
|
495
|
+
const configPath = absolute(flags.config ?? defaultConfigPath(client, env, context), context);
|
|
496
|
+
const credentialsPath = absolute(flags.credentialsFile ?? env.PAYMOS_CREDENTIALS_FILE ?? join(env.XDG_CONFIG_HOME || join(context.home, ".config"), "paymos", "mcp", "credentials.json"), context);
|
|
497
|
+
const samePath3 = context.platform === "win32" ? configPath.toLowerCase() === credentialsPath.toLowerCase() : configPath === credentialsPath;
|
|
498
|
+
if (samePath3 || !isAbsolute(configPath) || !isAbsolute(credentialsPath)) error("conflict");
|
|
499
|
+
const before = snapshot(configPath);
|
|
500
|
+
const beforeKeys = snapshot(credentialsPath);
|
|
501
|
+
const stored = beforeKeys.content === null ? void 0 : readCredentialFile(credentialsPath);
|
|
502
|
+
const apiKeyId = (env.PAYMOS_API_KEY_ID ?? stored?.apiKeyId ?? await ask(io, SETUP_COPY.apiKey)).trim();
|
|
503
|
+
const apiSecret = (env.PAYMOS_API_SECRET ?? stored?.apiSecret ?? await ask(io, SETUP_COPY.apiSecret, true)).trim();
|
|
504
|
+
const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? stored?.webhookSecret ?? (io.interactive ? await ask(io, SETUP_COPY.webhookSecret, true) : "")).trim();
|
|
505
|
+
const credentials = {
|
|
506
|
+
apiKeyId,
|
|
507
|
+
apiSecret,
|
|
508
|
+
...webhookSecret === "" ? {} : { webhookSecret }
|
|
509
|
+
};
|
|
510
|
+
if (!checkCredentials(credentials).ok) error("credentials");
|
|
511
|
+
if (stored !== void 0 && !isDeepStrictEqual(stored, credentials)) error("conflict");
|
|
512
|
+
const next = planClientConfig(client, before.content, credentialsPath, context.platform);
|
|
513
|
+
if (flags.dryRun) {
|
|
514
|
+
io.log(SETUP_COPY.preview(configPath));
|
|
515
|
+
io.log(SETUP_COPY.preview(credentialsPath));
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
if (before.content === next && stored !== void 0) {
|
|
519
|
+
io.log(SETUP_COPY.unchanged(configPath));
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
let createdKeys;
|
|
523
|
+
try {
|
|
524
|
+
withDestinationLock(configPath, () => {
|
|
525
|
+
assertUnchanged(before);
|
|
526
|
+
assertUnchanged(beforeKeys);
|
|
527
|
+
if (stored === void 0) {
|
|
528
|
+
createdKeys = writeConfig(beforeKeys, JSON.stringify(credentials, null, 2) + "\n");
|
|
529
|
+
}
|
|
530
|
+
if (before.content !== next) writeConfig(before, next);
|
|
531
|
+
});
|
|
532
|
+
} catch (cause) {
|
|
533
|
+
if (cause instanceof DestinationBusyError) error("changed");
|
|
534
|
+
if (createdKeys !== void 0) {
|
|
535
|
+
try {
|
|
536
|
+
const stat2 = lstatSync3(credentialsPath, { bigint: true });
|
|
537
|
+
if (!stat2.isSymbolicLink() && sameIdentity2(stat2, createdKeys) && isDeepStrictEqual(readCredentialFile(credentialsPath), credentials)) unlinkSync2(credentialsPath);
|
|
538
|
+
} catch {
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
|
|
542
|
+
error("write");
|
|
543
|
+
}
|
|
544
|
+
io.log(SETUP_COPY.configured(configPath));
|
|
545
|
+
io.log(SETUP_COPY.restart);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/auth.ts
|
|
549
|
+
var remoteUrl = "https://app.paymos.io/connect/merchant-mcp";
|
|
550
|
+
var remoteEntries = {
|
|
551
|
+
codex: {
|
|
552
|
+
url: remoteUrl,
|
|
553
|
+
scopes: ["merchant:mcp", "offline_access"],
|
|
554
|
+
oauth: {
|
|
555
|
+
client_id: "paymos-merchant-codex",
|
|
556
|
+
callback_port: 33419,
|
|
557
|
+
callback_url: "http://127.0.0.1:33419/callback"
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
"claude-code": {
|
|
561
|
+
type: "http",
|
|
562
|
+
url: remoteUrl,
|
|
563
|
+
oauth: { clientId: "paymos-merchant-claude-code", callbackPort: 33420, scopes: "merchant:mcp offline_access" }
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
var AuthError = class extends Error {
|
|
567
|
+
constructor(code) {
|
|
568
|
+
super(code + ": " + AUTH_COPY.errors[code]);
|
|
569
|
+
this.code = code;
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
function fail(code) {
|
|
573
|
+
throw new AuthError(code);
|
|
574
|
+
}
|
|
575
|
+
async function chooseClient(argv, io) {
|
|
576
|
+
let input;
|
|
577
|
+
if (argv.length === 2 && argv[0] === "--client") input = argv[1];
|
|
578
|
+
else if (argv.length === 1 && argv[0]?.startsWith("--client=")) input = argv[0].slice(9);
|
|
579
|
+
else if (argv.length === 0 && io.interactive) {
|
|
580
|
+
try {
|
|
581
|
+
input = (await io.ask(AUTH_COPY.chooseClient, false)).trim();
|
|
582
|
+
} catch {
|
|
583
|
+
return fail("auth_cancelled");
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
if (input === "codex" || input === "claude-code") return input;
|
|
587
|
+
return fail("client_required");
|
|
588
|
+
}
|
|
589
|
+
function samePath(left, right, platform) {
|
|
590
|
+
if (platform === "win32") return resolve2(left).toLowerCase() === resolve2(right).toLowerCase();
|
|
591
|
+
return resolve2(left) === resolve2(right);
|
|
592
|
+
}
|
|
593
|
+
function inside(root, path) {
|
|
594
|
+
const tail = relative(root, path);
|
|
595
|
+
return tail === "" || tail !== ".." && !tail.startsWith(".." + sep) && !isAbsolute2(tail);
|
|
596
|
+
}
|
|
597
|
+
function stat(path) {
|
|
598
|
+
return lstatSync4(path, { throwIfNoEntry: false });
|
|
599
|
+
}
|
|
600
|
+
function projectDirectories(context) {
|
|
601
|
+
const dirs = [];
|
|
602
|
+
for (let dir = context.cwd; ; dir = dirname3(dir)) {
|
|
603
|
+
dirs.push(dir);
|
|
604
|
+
if (stat(join2(dir, ".git"))) return { dirs, repository: dir };
|
|
605
|
+
if (dir === dirname3(dir) || samePath(dir, context.home, context.platform)) return { dirs };
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function systemRoot(value, fallback) {
|
|
609
|
+
if (value && !isAbsolute2(value)) return fail("configuration_scope_unknown");
|
|
610
|
+
return resolve2(value || fallback);
|
|
611
|
+
}
|
|
612
|
+
function windowsPaths(env, home) {
|
|
613
|
+
return {
|
|
614
|
+
programFiles: systemRoot(env.ProgramFiles, join2(parse(home).root, "Program Files")),
|
|
615
|
+
programData: systemRoot(env.ProgramData, join2(parse(home).root, "ProgramData")),
|
|
616
|
+
appData: systemRoot(env.APPDATA, join2(home, "AppData", "Roaming")),
|
|
617
|
+
localAppData: systemRoot(env.LOCALAPPDATA, join2(home, "AppData", "Local"))
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function fixedFile(path, platform, allowedRoot = dirname3(path)) {
|
|
621
|
+
const info = stat(path);
|
|
622
|
+
if (!info) return void 0;
|
|
623
|
+
const real = realpathSync(path);
|
|
624
|
+
if (!inside(allowedRoot, real) || !stat(real)?.isFile() || platform === "win32" && (info.isSymbolicLink() || !samePath(path, real, platform))) {
|
|
625
|
+
return fail("client_installation_unknown");
|
|
626
|
+
}
|
|
627
|
+
if (platform !== "win32") accessSync(real, constants3.X_OK);
|
|
628
|
+
return real;
|
|
629
|
+
}
|
|
630
|
+
function packageLauncher(modules, client, platform) {
|
|
631
|
+
const name = client === "codex" ? "@openai/codex" : "@anthropic-ai/claude-code";
|
|
632
|
+
const command = client === "codex" ? "codex" : "claude";
|
|
633
|
+
const root = join2(modules, name);
|
|
634
|
+
const info = stat(root);
|
|
635
|
+
if (!info) return void 0;
|
|
636
|
+
if (!info.isDirectory() || !samePath(realpathSync(root), root, platform)) return fail("client_installation_unknown");
|
|
637
|
+
const manifest = parseConfig("jsonc", snapshot(join2(root, "package.json")).content);
|
|
638
|
+
const bin = object(manifest.bin) ? manifest.bin[command] : void 0;
|
|
639
|
+
const nativeBin = platform === "win32" ? "bin/claude.exe" : "bin/claude";
|
|
640
|
+
const fixedBins = client === "codex" ? ["bin/codex.js"] : ["cli.js", nativeBin];
|
|
641
|
+
if (manifest.name !== name || typeof bin !== "string" || !fixedBins.includes(bin)) {
|
|
642
|
+
return fail("client_installation_unknown");
|
|
643
|
+
}
|
|
644
|
+
const binary = fixedFile(join2(root, bin), platform, root);
|
|
645
|
+
if (!binary) return fail("client_installation_unknown");
|
|
646
|
+
if (bin === nativeBin) return { executable: binary };
|
|
647
|
+
const node = isAbsolute2(process.execPath) ? realpathSync(process.execPath) : void 0;
|
|
648
|
+
if (!node || !stat(node)?.isFile()) return fail("client_installation_unknown");
|
|
649
|
+
return { executable: node, jsBin: binary };
|
|
650
|
+
}
|
|
651
|
+
function resolveLaunch(client, context, env, repository) {
|
|
652
|
+
const { home, platform } = context;
|
|
653
|
+
const command = client === "codex" ? "codex" : "claude";
|
|
654
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
655
|
+
const outsideRepository = (path) => !repository || !inside(repository, path);
|
|
656
|
+
const add = (launch) => {
|
|
657
|
+
if (!launch) return;
|
|
658
|
+
const bin = launch.jsBin ?? launch.executable;
|
|
659
|
+
if (!outsideRepository(bin) || !outsideRepository(launch.executable)) return fail("client_installation_unknown");
|
|
660
|
+
candidates.set(platform === "win32" ? bin.toLowerCase() : bin, launch);
|
|
661
|
+
};
|
|
662
|
+
try {
|
|
663
|
+
if (platform === "win32") {
|
|
664
|
+
const paths = windowsPaths(env, home);
|
|
665
|
+
for (const prefix of [join2(paths.appData, "npm"), join2(paths.programFiles, "nodejs")]) {
|
|
666
|
+
if (!outsideRepository(prefix)) return fail("client_installation_unknown");
|
|
667
|
+
add(packageLauncher(join2(prefix, "node_modules"), client, platform));
|
|
668
|
+
}
|
|
669
|
+
const exe = command + ".exe";
|
|
670
|
+
const installed = client === "codex" ? join2(paths.localAppData, "Programs", "OpenAI", "Codex", "bin", exe) : join2(home, ".local", "bin", exe);
|
|
671
|
+
if (stat(installed)) {
|
|
672
|
+
const resolved = realpathSync(installed);
|
|
673
|
+
const releases = join2(home, ".codex", "packages", "standalone", "releases");
|
|
674
|
+
if (client === "codex" && !samePath(installed, resolved, platform)) {
|
|
675
|
+
const target = relative(releases, resolved).split(sep).join("/");
|
|
676
|
+
if (!/^[\d][\w.-]*-(?:x86_64|aarch64)-pc-windows-msvc\/(?:bin\/)?codex\.exe$/i.test(target)) {
|
|
677
|
+
return fail("client_installation_unknown");
|
|
678
|
+
}
|
|
679
|
+
add({ executable: fixedFile(resolved, platform, releases) });
|
|
680
|
+
} else {
|
|
681
|
+
add({ executable: fixedFile(installed, platform) });
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const wingetRoot = client === "codex" ? "OpenAI.Codex" : "Anthropic.ClaudeCode";
|
|
685
|
+
const wingetName = client === "codex" ? "codex-" + (process.arch === "arm64" ? "aarch64" : "x86_64") + "-pc-windows-msvc.exe" : exe;
|
|
686
|
+
for (const base of [join2(paths.localAppData, "Microsoft"), paths.programFiles]) {
|
|
687
|
+
const packageDir = join2(base, "WinGet", "Packages", wingetRoot + "_Microsoft.Winget.Source_8wekyb3d8bbwe");
|
|
688
|
+
const absolute2 = fixedFile(join2(packageDir, wingetName), platform);
|
|
689
|
+
if (absolute2) add({ executable: absolute2 });
|
|
690
|
+
}
|
|
691
|
+
} else {
|
|
692
|
+
const userBin = join2(home, ".local", "bin", command);
|
|
693
|
+
if (stat(userBin)) {
|
|
694
|
+
const releases = client === "codex" ? join2(home, ".codex", "packages", "standalone", "releases") : join2(home, ".local", "share", "claude", "versions");
|
|
695
|
+
const userRoot = stat(userBin)?.isSymbolicLink() ? releases : dirname3(userBin);
|
|
696
|
+
const executable = fixedFile(userBin, platform, userRoot);
|
|
697
|
+
if (executable) add({ executable });
|
|
698
|
+
}
|
|
699
|
+
for (const prefix of /* @__PURE__ */ new Set(["/usr", "/usr/local", "/opt/homebrew", dirname3(dirname3(process.execPath))])) {
|
|
700
|
+
if (!isAbsolute2(prefix) || !outsideRepository(prefix)) continue;
|
|
701
|
+
add(packageLauncher(join2(prefix, "lib", "node_modules"), client, platform));
|
|
702
|
+
}
|
|
703
|
+
for (const prefix of ["/usr", "/usr/local", "/opt/homebrew"]) {
|
|
704
|
+
const executable = fixedFile(join2(prefix, "bin", command), platform, prefix);
|
|
705
|
+
if (executable && !executable.endsWith(".js")) add({ executable });
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
} catch {
|
|
709
|
+
return fail("client_installation_unknown");
|
|
710
|
+
}
|
|
711
|
+
if (candidates.size !== 1) return fail("client_installation_unknown");
|
|
712
|
+
return candidates.values().next().value;
|
|
713
|
+
}
|
|
714
|
+
function sandboxEntry(value) {
|
|
715
|
+
if (!object(value) || Object.hasOwn(value, "url") || Object.hasOwn(value, "oauth") || value.type !== void 0 && value.type !== "stdio") return false;
|
|
716
|
+
return value.command === "npx" && equalData(value.args, ["-y", "@paymos/mcp"]) || value.command === "cmd" && equalData(value.args, ["/d", "/c", "npx", "-y", "@paymos/mcp"]) || value.command === "paymos-mcp" && (value.args === void 0 || equalData(value.args, []));
|
|
717
|
+
}
|
|
718
|
+
function assertConfigLocation(path, platform) {
|
|
719
|
+
if (!isAbsolute2(path)) fail("configuration_scope_unknown");
|
|
720
|
+
for (let parent = dirname3(path); ; parent = dirname3(parent)) {
|
|
721
|
+
const info = stat(parent);
|
|
722
|
+
if (info) {
|
|
723
|
+
if (!info.isDirectory() || !samePath(parent, realpathSync(parent), platform)) fail("configuration_scope_unknown");
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (parent === dirname3(parent)) fail("configuration_scope_unknown");
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
function preflight(client, context, env, dirs) {
|
|
730
|
+
const { home, platform } = context;
|
|
731
|
+
const windows = platform === "win32" ? windowsPaths(env, home) : void 0;
|
|
732
|
+
const format = client === "codex" ? "toml" : "jsonc";
|
|
733
|
+
const group = client === "codex" ? "mcp_servers" : "mcpServers";
|
|
734
|
+
const target = defaultConfigPath(client, env, context);
|
|
735
|
+
const watched = /* @__PURE__ */ new Map();
|
|
736
|
+
const layers = [];
|
|
737
|
+
const disabled = /* @__PURE__ */ new Set();
|
|
738
|
+
const read = (path, type = format) => {
|
|
739
|
+
assertConfigLocation(path, platform);
|
|
740
|
+
let before = watched.get(path);
|
|
741
|
+
if (!before) {
|
|
742
|
+
before = snapshot(path);
|
|
743
|
+
watched.set(path, before);
|
|
744
|
+
}
|
|
745
|
+
return parseConfig(type, before.content);
|
|
746
|
+
};
|
|
747
|
+
const rejectManagedFiles = (paths) => {
|
|
748
|
+
for (const path of paths) {
|
|
749
|
+
if (stat(path)) fail("configuration_scope_unknown");
|
|
750
|
+
watched.set(path, { path, content: null });
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
try {
|
|
754
|
+
const user = read(target);
|
|
755
|
+
if (client === "codex") {
|
|
756
|
+
const system = windows ? join2(windows.programData, "OpenAI", "Codex") : resolve2("/etc/codex");
|
|
757
|
+
rejectManagedFiles([
|
|
758
|
+
join2(system, "managed_config.toml"),
|
|
759
|
+
join2(system, "requirements.toml"),
|
|
760
|
+
join2(dirname3(target), "managed_config.toml"),
|
|
761
|
+
join2(dirname3(target), "requirements.toml")
|
|
762
|
+
]);
|
|
763
|
+
if (env.CODEX_PROFILE || user.profile !== void 0) fail("configuration_scope_unknown");
|
|
764
|
+
const projects = [join2(context.cwd, "config.toml"), ...dirs.map((dir) => join2(dir, ".codex", "config.toml"))];
|
|
765
|
+
const roots = [
|
|
766
|
+
...projects.filter((path) => !samePath(path, target, platform)).map((path) => read(path)),
|
|
767
|
+
user,
|
|
768
|
+
read(join2(system, "config.toml"))
|
|
769
|
+
];
|
|
770
|
+
for (const root of roots) {
|
|
771
|
+
if (root.project_root_markers !== void 0 && !equalData(root.project_root_markers, [".git"])) {
|
|
772
|
+
fail("configuration_scope_unknown");
|
|
773
|
+
}
|
|
774
|
+
layers.push(configEntries(root, group));
|
|
775
|
+
}
|
|
776
|
+
} else {
|
|
777
|
+
const userConfig = join2(home, ".claude");
|
|
778
|
+
if (env.CLAUDE_CONFIG_DIR && !samePath(env.CLAUDE_CONFIG_DIR, userConfig, platform)) fail("configuration_scope_unknown");
|
|
779
|
+
const systems = windows ? [join2(windows.programFiles, "ClaudeCode"), join2(windows.programData, "ClaudeCode")] : [resolve2(platform === "darwin" ? "/Library/Application Support/ClaudeCode" : "/etc/claude-code")];
|
|
780
|
+
rejectManagedFiles([...systems, userConfig].flatMap((dir) => ["managed-mcp.json", "managed-settings.json", "managed-settings.d"].map((name2) => join2(dir, name2))));
|
|
781
|
+
const noteDisabled = (root) => {
|
|
782
|
+
for (const key of ["disabledMcpServers", "disabledMcpjsonServers"]) {
|
|
783
|
+
const entries2 = root[key];
|
|
784
|
+
if (entries2 === void 0) continue;
|
|
785
|
+
if (!Array.isArray(entries2)) return fail("configuration_scope_unknown");
|
|
786
|
+
for (const name2 of entries2) disabled.add(name2);
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
const localProjects = configEntries(user, "projects");
|
|
790
|
+
for (const dir of dirs) {
|
|
791
|
+
for (const [path, settings] of Object.entries(localProjects)) {
|
|
792
|
+
if (!isAbsolute2(path) || !samePath(path, dir, platform)) continue;
|
|
793
|
+
if (!object(settings)) return fail("configuration_scope_unknown");
|
|
794
|
+
layers.push(configEntries(settings, group));
|
|
795
|
+
noteDisabled(settings);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
for (const dir of dirs) layers.push(configEntries(read(join2(dir, ".mcp.json")), group));
|
|
799
|
+
layers.push(configEntries(user, group));
|
|
800
|
+
noteDisabled(user);
|
|
801
|
+
const settingsPaths = [join2(userConfig, "settings.json"), ...dirs.flatMap((dir) => ["settings.json", "settings.local.json"].map((name2) => join2(dir, ".claude", name2)))];
|
|
802
|
+
for (const path of settingsPaths) {
|
|
803
|
+
const settings = read(path);
|
|
804
|
+
if (["allowManagedMcpServersOnly", "allowedMcpServers", "deniedMcpServers"].some((key) => settings[key] !== void 0)) fail("configuration_scope_unknown");
|
|
805
|
+
noteDisabled(settings);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const profile = remoteEntries[client];
|
|
809
|
+
const entries = (name2) => layers.filter((layer) => Object.hasOwn(layer, name2)).map((layer) => layer[name2]);
|
|
810
|
+
const primary = entries("paymos");
|
|
811
|
+
const alternate = entries("paymos-merchant");
|
|
812
|
+
if (primary.some((value) => !equalData(value, profile) && !sandboxEntry(value))) fail("configuration_conflict");
|
|
813
|
+
const name = primary.some(sandboxEntry) || primary.length === 0 && alternate.some((value) => equalData(value, profile)) ? "paymos-merchant" : "paymos";
|
|
814
|
+
const chosen = entries(name);
|
|
815
|
+
if (disabled.has(name) || chosen.some((value) => !equalData(value, profile))) fail("configuration_conflict");
|
|
816
|
+
const before = watched.get(target);
|
|
817
|
+
const next = chosen.length === 0 ? planConfigEntry(format, before.content, group, name, profile) : before.content;
|
|
818
|
+
return { name, before, next, watched: [...watched.values()] };
|
|
819
|
+
} catch (cause) {
|
|
820
|
+
if (cause instanceof AuthError) throw cause;
|
|
821
|
+
return fail("configuration_scope_unknown");
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
function nativeLogin(launch, name, cwd, env) {
|
|
825
|
+
const args = [...launch.jsBin ? [launch.jsBin] : [], "mcp", "login", name];
|
|
826
|
+
const childEnv = { ...env };
|
|
827
|
+
if (launch.jsBin) {
|
|
828
|
+
for (const key of Object.keys(childEnv)) {
|
|
829
|
+
if (["NODE_OPTIONS", "NODE_PATH"].includes(key.toUpperCase())) delete childEnv[key];
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
return new Promise((accept, reject) => {
|
|
833
|
+
let child;
|
|
834
|
+
let signal;
|
|
835
|
+
const interrupt = (reason) => {
|
|
836
|
+
signal ??= reason;
|
|
837
|
+
if (child && child.exitCode === null && child.signalCode === null) child.kill(reason);
|
|
838
|
+
};
|
|
839
|
+
const onInt = () => interrupt("SIGINT");
|
|
840
|
+
const onTerm = () => interrupt("SIGTERM");
|
|
841
|
+
const cleanup = () => {
|
|
842
|
+
process.removeListener("SIGINT", onInt);
|
|
843
|
+
process.removeListener("SIGTERM", onTerm);
|
|
844
|
+
};
|
|
845
|
+
process.on("SIGINT", onInt);
|
|
846
|
+
process.on("SIGTERM", onTerm);
|
|
847
|
+
try {
|
|
848
|
+
child = spawn(launch.executable, args, { cwd, env: childEnv, shell: false, stdio: "inherit" });
|
|
849
|
+
child.once("error", () => {
|
|
850
|
+
cleanup();
|
|
851
|
+
reject(new AuthError("auth_failed"));
|
|
852
|
+
});
|
|
853
|
+
child.once("close", (code, childSignal) => {
|
|
854
|
+
cleanup();
|
|
855
|
+
const reason = signal ?? childSignal;
|
|
856
|
+
accept(reason === "SIGINT" ? 130 : reason === "SIGTERM" ? 143 : code ?? 1);
|
|
857
|
+
});
|
|
858
|
+
} catch {
|
|
859
|
+
cleanup();
|
|
860
|
+
reject(new AuthError("auth_failed"));
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
async function runAuth(argv, env = process.env, io = terminalIO(), input = { home: homedir2(), cwd: process.cwd(), platform: process.platform }) {
|
|
865
|
+
if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "-h")) {
|
|
866
|
+
io.log(AUTH_COPY.help);
|
|
867
|
+
return 0;
|
|
868
|
+
}
|
|
869
|
+
let client;
|
|
870
|
+
try {
|
|
871
|
+
client = await chooseClient(argv, io);
|
|
872
|
+
} catch (cause) {
|
|
873
|
+
if (!(cause instanceof AuthError) || cause.code !== "auth_cancelled") throw cause;
|
|
874
|
+
io.log(cause.message);
|
|
875
|
+
return 130;
|
|
876
|
+
}
|
|
877
|
+
let context;
|
|
878
|
+
let project;
|
|
879
|
+
try {
|
|
880
|
+
if (env.GIT_DIR || env.GIT_WORK_TREE) return fail("configuration_scope_unknown");
|
|
881
|
+
context = { ...input, cwd: realpathSync(input.cwd), home: realpathSync(input.home) };
|
|
882
|
+
project = projectDirectories(context);
|
|
883
|
+
} catch {
|
|
884
|
+
return fail("configuration_scope_unknown");
|
|
885
|
+
}
|
|
886
|
+
const launch = resolveLaunch(client, context, env, project.repository);
|
|
887
|
+
const plan = preflight(client, context, env, project.dirs);
|
|
888
|
+
const next = plan.next;
|
|
889
|
+
const assertPlanUnchanged = () => {
|
|
890
|
+
for (const before of plan.watched) {
|
|
891
|
+
assertConfigLocation(before.path, context.platform);
|
|
892
|
+
assertUnchanged(before);
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
let published;
|
|
896
|
+
try {
|
|
897
|
+
if (next !== null && next !== plan.before.content) {
|
|
898
|
+
published = withDestinationLock(plan.before.path, () => {
|
|
899
|
+
assertPlanUnchanged();
|
|
900
|
+
return writeConfig(plan.before, next);
|
|
901
|
+
});
|
|
902
|
+
} else {
|
|
903
|
+
assertPlanUnchanged();
|
|
904
|
+
}
|
|
905
|
+
} catch (cause) {
|
|
906
|
+
if (cause instanceof AuthError) throw cause;
|
|
907
|
+
if (cause instanceof DestinationBusyError || cause instanceof Error && cause.message === SETUP_COPY.errors.changed) {
|
|
908
|
+
return fail("configuration_conflict");
|
|
909
|
+
}
|
|
910
|
+
return fail("configuration_write_failed");
|
|
911
|
+
}
|
|
912
|
+
const restore = () => {
|
|
913
|
+
if (published === void 0 || next === null) return;
|
|
914
|
+
let restored = false;
|
|
915
|
+
try {
|
|
916
|
+
assertConfigLocation(plan.before.path, context.platform);
|
|
917
|
+
restored = withDestinationLock(plan.before.path, () => {
|
|
918
|
+
assertConfigLocation(plan.before.path, context.platform);
|
|
919
|
+
return restoreConfig(plan.before, next, published);
|
|
920
|
+
});
|
|
921
|
+
} catch {
|
|
922
|
+
}
|
|
923
|
+
if (!restored) io.log("configuration_restore_skipped: " + AUTH_COPY.errors.configuration_restore_skipped);
|
|
924
|
+
};
|
|
925
|
+
let code;
|
|
926
|
+
try {
|
|
927
|
+
code = await nativeLogin(launch, plan.name, context.cwd, env);
|
|
928
|
+
} catch (cause) {
|
|
929
|
+
restore();
|
|
930
|
+
throw cause;
|
|
931
|
+
}
|
|
932
|
+
if (code === 0) return code;
|
|
933
|
+
restore();
|
|
934
|
+
const error2 = code === 130 || code === 143 ? "auth_cancelled" : "auth_failed";
|
|
935
|
+
io.log(error2 + ": " + AUTH_COPY.errors[error2]);
|
|
936
|
+
return code;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// src/config.ts
|
|
940
|
+
var FLAG_NAMES = /* @__PURE__ */ new Map([
|
|
941
|
+
["--api-key-id", "apiKeyId"],
|
|
942
|
+
["--api-secret", "apiSecret"]
|
|
943
|
+
]);
|
|
944
|
+
function parseFlags(argv) {
|
|
945
|
+
const flags = {};
|
|
946
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
947
|
+
const token = argv[index];
|
|
948
|
+
if (token === void 0 || token === "--") break;
|
|
949
|
+
const equals = token.indexOf("=");
|
|
950
|
+
const head = equals < 0 ? token : token.slice(0, equals);
|
|
951
|
+
const field = FLAG_NAMES.get(head);
|
|
952
|
+
if (!field) continue;
|
|
953
|
+
const value = equals < 0 ? argv[index + 1] : token.slice(equals + 1);
|
|
954
|
+
if (value === void 0) break;
|
|
955
|
+
flags[field] = value;
|
|
956
|
+
if (equals < 0) index += 1;
|
|
957
|
+
}
|
|
958
|
+
return flags;
|
|
959
|
+
}
|
|
960
|
+
function loadCredentials(env, flags) {
|
|
961
|
+
const file = env.PAYMOS_CREDENTIALS_FILE === void 0 ? void 0 : readCredentialFile(env.PAYMOS_CREDENTIALS_FILE);
|
|
962
|
+
const apiKeyId = (env.PAYMOS_API_KEY_ID ?? flags.apiKeyId ?? file?.apiKeyId ?? "").trim();
|
|
963
|
+
const apiSecret = (env.PAYMOS_API_SECRET ?? flags.apiSecret ?? file?.apiSecret ?? "").trim();
|
|
964
|
+
const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? file?.webhookSecret ?? "").trim();
|
|
965
|
+
return webhookSecret === "" ? { apiKeyId, apiSecret } : { apiKeyId, apiSecret, webhookSecret };
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// src/files.ts
|
|
969
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
|
|
970
|
+
import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync4, linkSync as linkSync2, lstatSync as lstatSync6, openSync as openSync4, readSync, unlinkSync as unlinkSync4 } from "fs";
|
|
971
|
+
import { open } from "fs/promises";
|
|
972
|
+
import { dirname as dirname4, join as join4 } from "path";
|
|
973
|
+
|
|
974
|
+
// src/install-secret.ts
|
|
975
|
+
import { spawnSync } from "child_process";
|
|
976
|
+
import { createHash, randomBytes } from "crypto";
|
|
977
|
+
import { lstatSync as lstatSync5, mkdirSync as mkdirSync3, readdirSync, realpathSync as realpathSync2, unlinkSync as unlinkSync3 } from "fs";
|
|
978
|
+
import { userInfo } from "os";
|
|
979
|
+
import { isAbsolute as isAbsolute3, join as join3, parse as parse2, relative as relative2, resolve as resolve3, sep as sep2 } from "path";
|
|
980
|
+
import { parseEnv } from "util";
|
|
981
|
+
var origin = "https://app.paymos.io";
|
|
982
|
+
var resource = "/connect/merchant-mcp";
|
|
983
|
+
var lifetimeMs = 5 * 6e4;
|
|
984
|
+
var requestTimeoutMs = 6e4;
|
|
985
|
+
var stateFolder = ".paymos-mcp-delivery";
|
|
986
|
+
var uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
|
|
987
|
+
var windowsStateScript = String.raw`
|
|
988
|
+
using namespace System.IO
|
|
989
|
+
using namespace System.Security.AccessControl
|
|
990
|
+
using namespace System.Security.Principal
|
|
991
|
+
|
|
992
|
+
$ErrorActionPreference = 'Stop'
|
|
993
|
+
try {
|
|
994
|
+
$path = [Environment]::GetEnvironmentVariable('PAYMOS_DELIVERY_STATE_PATH')
|
|
995
|
+
$action = [Environment]::GetEnvironmentVariable('PAYMOS_DELIVERY_STATE_ACTION')
|
|
996
|
+
$sid = [WindowsIdentity]::GetCurrent().User
|
|
997
|
+
$rights = [FileSystemRights]::FullControl
|
|
998
|
+
$sections = [AccessControlSections]'Access, Owner'
|
|
999
|
+
|
|
1000
|
+
function New-PrivateAcl([bool] $directory) {
|
|
1001
|
+
if ($directory) {
|
|
1002
|
+
$acl = [DirectorySecurity]::new()
|
|
1003
|
+
$inheritance = [InheritanceFlags]'ContainerInherit, ObjectInherit'
|
|
1004
|
+
} else {
|
|
1005
|
+
$acl = [FileSecurity]::new()
|
|
1006
|
+
$inheritance = [InheritanceFlags]::None
|
|
1007
|
+
}
|
|
1008
|
+
$acl.SetOwner($sid)
|
|
1009
|
+
$acl.SetAccessRuleProtection($true, $false)
|
|
1010
|
+
$acl.AddAccessRule([FileSystemAccessRule]::new($sid, $rights, $inheritance,
|
|
1011
|
+
[PropagationFlags]::None, [AccessControlType]::Allow))
|
|
1012
|
+
return $acl
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function Assert-OrdinaryPath([string] $item, [bool] $directory) {
|
|
1016
|
+
$attributes = [File]::GetAttributes($item)
|
|
1017
|
+
if (($attributes -band [FileAttributes]::ReparsePoint) -or
|
|
1018
|
+
([bool]($attributes -band [FileAttributes]::Directory) -ne $directory)) {
|
|
1019
|
+
throw 'Unexpected filesystem object'
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function Assert-PrivateAcl([FileSystemSecurity] $acl, [AceFlags] $flags) {
|
|
1024
|
+
$descriptor = [RawSecurityDescriptor]::new($acl.GetSecurityDescriptorBinaryForm(), 0)
|
|
1025
|
+
if (!$acl.AreAccessRulesProtected -or $descriptor.Owner.Value -ne $sid.Value -or
|
|
1026
|
+
$descriptor.DiscretionaryAcl.Count -ne 1) { throw 'Unexpected state ACL' }
|
|
1027
|
+
$rule = $descriptor.DiscretionaryAcl[0]
|
|
1028
|
+
if ($rule.AceType -ne [AceType]::AccessAllowed -or $rule.AceFlags -ne $flags -or
|
|
1029
|
+
$rule.AccessMask -ne [int]$rights -or $rule.SecurityIdentifier.Value -ne $sid.Value) {
|
|
1030
|
+
throw 'Unexpected state access rule'
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function Assert-PrivateDirectory([string] $directory) {
|
|
1035
|
+
Assert-OrdinaryPath $directory $true
|
|
1036
|
+
Assert-PrivateAcl ([Directory]::GetAccessControl($directory, $sections)) ([AceFlags]'ContainerInherit, ObjectInherit')
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
switch ($action) {
|
|
1040
|
+
'write-file' {
|
|
1041
|
+
$directory = [Path]::GetDirectoryName($path)
|
|
1042
|
+
Assert-OrdinaryPath ([Path]::GetDirectoryName($directory)) $true
|
|
1043
|
+
[void][Directory]::CreateDirectory($directory, (New-PrivateAcl $true))
|
|
1044
|
+
Assert-PrivateDirectory $directory
|
|
1045
|
+
$staged = [Path]::Combine($directory, '.paymos-' + [Guid]::NewGuid().ToString('N') + '.tmp')
|
|
1046
|
+
$file = [FileStream]::new($staged, [FileMode]::CreateNew, $rights,
|
|
1047
|
+
[FileShare]::None, 4096, [FileOptions]::None, (New-PrivateAcl $false))
|
|
1048
|
+
try {
|
|
1049
|
+
try {
|
|
1050
|
+
Assert-PrivateAcl ($file.GetAccessControl()) ([AceFlags]::None)
|
|
1051
|
+
[Console]::OpenStandardInput().CopyTo($file)
|
|
1052
|
+
$file.Flush($true)
|
|
1053
|
+
} finally { $file.Dispose() }
|
|
1054
|
+
# Same-directory move keeps the protected ACL and refuses to replace an existing file.
|
|
1055
|
+
[File]::Move($staged, $path)
|
|
1056
|
+
} catch {
|
|
1057
|
+
[File]::Delete($staged)
|
|
1058
|
+
throw
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
'check-file' {
|
|
1062
|
+
Assert-PrivateDirectory ([Path]::GetDirectoryName($path))
|
|
1063
|
+
Assert-OrdinaryPath $path $false
|
|
1064
|
+
Assert-PrivateAcl ([File]::GetAccessControl($path, $sections)) ([AceFlags]::None)
|
|
1065
|
+
}
|
|
1066
|
+
default { throw 'Unexpected action' }
|
|
1067
|
+
}
|
|
1068
|
+
} catch { exit 1 }
|
|
1069
|
+
`;
|
|
1070
|
+
function defaultDeliveryRuntime() {
|
|
1071
|
+
return {
|
|
1072
|
+
cwd: process.cwd(),
|
|
1073
|
+
home: userInfo().homedir,
|
|
1074
|
+
platform: process.platform,
|
|
1075
|
+
now: Date.now,
|
|
1076
|
+
fetch: globalThis.fetch,
|
|
1077
|
+
stdout: (line) => console.log(line)
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
function failDelivery(code) {
|
|
1081
|
+
throw new MerchantDeliveryError(code);
|
|
1082
|
+
}
|
|
1083
|
+
async function safeDelivery(action) {
|
|
1084
|
+
try {
|
|
1085
|
+
await action();
|
|
1086
|
+
} catch (error2) {
|
|
1087
|
+
if (error2 instanceof MerchantDeliveryError) throw error2;
|
|
1088
|
+
failDelivery("delivery_local_io_failed");
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
function isBase64Url(value, length) {
|
|
1092
|
+
if (typeof value !== "string" || value.length !== Math.ceil(length * 4 / 3) || !/^[A-Za-z0-9_-]+$/.test(value)) return false;
|
|
1093
|
+
const bytes = Buffer.from(value, "base64url");
|
|
1094
|
+
return bytes.length === length && bytes.toString("base64url") === value;
|
|
1095
|
+
}
|
|
1096
|
+
function validUuid(value) {
|
|
1097
|
+
return typeof value === "string" && uuid.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
1098
|
+
}
|
|
1099
|
+
function deliveryArguments(argv, kind) {
|
|
1100
|
+
const fileOption = kind === "install-secret" ? "--env-file" : "--file";
|
|
1101
|
+
const common = [fileOption, "--merchant-id", "--environment", "--operation-id", "--request-id", "--token"];
|
|
1102
|
+
const flags = /* @__PURE__ */ new Map();
|
|
1103
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1104
|
+
const flag = argv[i];
|
|
1105
|
+
if (flags.has(flag)) failDelivery("delivery_arguments");
|
|
1106
|
+
if (flag === "--prepare") {
|
|
1107
|
+
flags.set(flag, "");
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
if (!common.includes(flag)) failDelivery("delivery_arguments");
|
|
1111
|
+
const value = argv[++i];
|
|
1112
|
+
if (!value || value.startsWith("--")) failDelivery("delivery_arguments");
|
|
1113
|
+
flags.set(flag, value);
|
|
1114
|
+
}
|
|
1115
|
+
const file = flags.get(fileOption);
|
|
1116
|
+
if (!file) return failDelivery("delivery_arguments");
|
|
1117
|
+
if (flags.has("--prepare")) {
|
|
1118
|
+
const merchantId = flags.get("--merchant-id")?.toLowerCase();
|
|
1119
|
+
const operationId = flags.get("--operation-id")?.toLowerCase();
|
|
1120
|
+
const environment = flags.get("--environment")?.toLowerCase();
|
|
1121
|
+
if (flags.size !== 5 || !validUuid(merchantId) || !validUuid(operationId) || environment !== "sandbox" && environment !== "production") return failDelivery("delivery_arguments");
|
|
1122
|
+
return { prepare: true, file, scope: { merchantId, environment, operationId } };
|
|
1123
|
+
}
|
|
1124
|
+
const requestId = flags.get("--request-id");
|
|
1125
|
+
const ticket = flags.get("--token");
|
|
1126
|
+
const prefix = kind === "install-secret" ? "otk_" : "ftk_";
|
|
1127
|
+
if (flags.size !== 3 || !isBase64Url(requestId, 32) || !ticket?.startsWith(prefix) || !isBase64Url(ticket.slice(prefix.length), kind === "upload-file" ? 48 : 32)) {
|
|
1128
|
+
return failDelivery("delivery_arguments");
|
|
1129
|
+
}
|
|
1130
|
+
return { prepare: false, file, requestId, ticket };
|
|
1131
|
+
}
|
|
1132
|
+
function pathStat(path) {
|
|
1133
|
+
return lstatSync5(path, { bigint: true, throwIfNoEntry: false });
|
|
1134
|
+
}
|
|
1135
|
+
function sameOpenFile(path, opened) {
|
|
1136
|
+
return path.isFile() && opened.isFile() && path.ino === opened.ino && path.birthtimeNs === opened.birthtimeNs && (path.dev === 0n || opened.dev === 0n || path.dev === opened.dev);
|
|
1137
|
+
}
|
|
1138
|
+
function samePath2(left, right, platform) {
|
|
1139
|
+
return platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
1140
|
+
}
|
|
1141
|
+
function inside2(directory, path) {
|
|
1142
|
+
const child = relative2(directory, path);
|
|
1143
|
+
return child !== ".." && !child.startsWith(".." + sep2) && !isAbsolute3(child);
|
|
1144
|
+
}
|
|
1145
|
+
function ordinaryDirectory(path, platform) {
|
|
1146
|
+
return !!pathStat(path)?.isDirectory() && samePath2(realpathSync2(path), path, platform);
|
|
1147
|
+
}
|
|
1148
|
+
function windowsStateAcl(action, path, input) {
|
|
1149
|
+
const systemRoot2 = process.env.SystemRoot;
|
|
1150
|
+
if (process.platform !== "win32" || !systemRoot2 || !/^[A-Za-z]:[\\/]/.test(systemRoot2)) {
|
|
1151
|
+
return failDelivery("delivery_state_unavailable");
|
|
1152
|
+
}
|
|
1153
|
+
const windows = resolve3(systemRoot2);
|
|
1154
|
+
const executable = join3(windows, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
1155
|
+
if (!pathStat(executable)?.isFile() || !samePath2(realpathSync2(executable), executable, "win32")) {
|
|
1156
|
+
return failDelivery("delivery_state_unavailable");
|
|
1157
|
+
}
|
|
1158
|
+
const result = spawnSync(executable, [
|
|
1159
|
+
"-NoLogo",
|
|
1160
|
+
"-NoProfile",
|
|
1161
|
+
"-NonInteractive",
|
|
1162
|
+
"-EncodedCommand",
|
|
1163
|
+
Buffer.from(windowsStateScript, "utf16le").toString("base64")
|
|
1164
|
+
], {
|
|
1165
|
+
cwd: windows,
|
|
1166
|
+
shell: false,
|
|
1167
|
+
stdio: [input === void 0 ? "ignore" : "pipe", "ignore", "ignore"],
|
|
1168
|
+
input,
|
|
1169
|
+
timeout: 1e4,
|
|
1170
|
+
windowsHide: true,
|
|
1171
|
+
env: { SystemRoot: windows, PAYMOS_DELIVERY_STATE_ACTION: action, PAYMOS_DELIVERY_STATE_PATH: path }
|
|
1172
|
+
});
|
|
1173
|
+
if (result.error || result.status !== 0) return failDelivery("delivery_state_unavailable");
|
|
1174
|
+
}
|
|
1175
|
+
function assertDeliveryTarget(target) {
|
|
1176
|
+
try {
|
|
1177
|
+
const segments = relative2(target.directory, target.path).split(sep2);
|
|
1178
|
+
let folder = target.directory;
|
|
1179
|
+
if (!ordinaryDirectory(folder, target.platform)) failDelivery("delivery_unsafe_path");
|
|
1180
|
+
for (const segment of segments.slice(0, -1)) {
|
|
1181
|
+
folder = join3(folder, segment);
|
|
1182
|
+
if (!ordinaryDirectory(folder, target.platform)) failDelivery("delivery_unsafe_path");
|
|
1183
|
+
}
|
|
1184
|
+
const stat2 = pathStat(target.path);
|
|
1185
|
+
if (stat2 && (!stat2.isFile() || stat2.nlink !== 1n || !samePath2(realpathSync2(target.path), target.path, target.platform))) {
|
|
1186
|
+
failDelivery("delivery_unsafe_path");
|
|
1187
|
+
}
|
|
1188
|
+
return stat2;
|
|
1189
|
+
} catch {
|
|
1190
|
+
return failDelivery("delivery_unsafe_path");
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
function deliveryTarget(file, runtime) {
|
|
1194
|
+
const tail = file.slice(parse2(file).root.length);
|
|
1195
|
+
const segments = tail.split(/[\\/]/);
|
|
1196
|
+
if (/\p{Cc}/u.test(file) || /^[\\/]{2}/.test(file) || segments.some((segment) => segment === ".." || segment.toLowerCase() === ".git") || runtime.platform === "win32" && /^[a-z]:/i.test(file) && !isAbsolute3(file) || runtime.platform === "win32" && segments.some((segment) => /[:*?"<>|]/.test(segment) || segment !== "." && /[. ]$/.test(segment) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segment)) || runtime.platform !== "win32" && file.includes("\\")) return failDelivery("delivery_unsafe_path");
|
|
1197
|
+
const directory = realpathSync2(runtime.cwd);
|
|
1198
|
+
const path = resolve3(directory, file);
|
|
1199
|
+
if (path === directory || !inside2(directory, path)) return failDelivery("delivery_unsafe_path");
|
|
1200
|
+
const target = { directory, path, platform: runtime.platform };
|
|
1201
|
+
assertDeliveryTarget(target);
|
|
1202
|
+
return target;
|
|
1203
|
+
}
|
|
1204
|
+
function stateDirectory(runtime, target, create) {
|
|
1205
|
+
try {
|
|
1206
|
+
const home = resolve3(runtime.home);
|
|
1207
|
+
if (!isAbsolute3(runtime.home) || !ordinaryDirectory(home, runtime.platform)) failDelivery("delivery_state_unavailable");
|
|
1208
|
+
const base = runtime.platform === "win32" ? join3(home, "AppData", "Local") : home;
|
|
1209
|
+
if (!ordinaryDirectory(base, runtime.platform)) return failDelivery("delivery_state_unavailable");
|
|
1210
|
+
const directory = join3(base, stateFolder);
|
|
1211
|
+
if (inside2(target.directory, directory) || inside2(directory, target.path)) failDelivery("delivery_unsafe_path");
|
|
1212
|
+
let stat2 = pathStat(directory);
|
|
1213
|
+
if (!stat2 && create) {
|
|
1214
|
+
if (runtime.platform === "win32") return directory;
|
|
1215
|
+
try {
|
|
1216
|
+
mkdirSync3(directory, { mode: 448 });
|
|
1217
|
+
} catch (cause) {
|
|
1218
|
+
if (cause.code !== "EEXIST") throw cause;
|
|
1219
|
+
}
|
|
1220
|
+
stat2 = pathStat(directory);
|
|
1221
|
+
}
|
|
1222
|
+
if (!stat2?.isDirectory() || !ordinaryDirectory(directory, runtime.platform) || runtime.platform !== "win32" && !privateMode(stat2)) {
|
|
1223
|
+
return failDelivery("delivery_state_unavailable");
|
|
1224
|
+
}
|
|
1225
|
+
return directory;
|
|
1226
|
+
} catch (cause) {
|
|
1227
|
+
if (cause instanceof MerchantDeliveryError) throw cause;
|
|
1228
|
+
return failDelivery("delivery_state_unavailable");
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
function privateMode(stat2) {
|
|
1232
|
+
return (stat2.mode & 0o077n) === 0n && (process.geteuid === void 0 || stat2.uid === BigInt(process.geteuid()));
|
|
1233
|
+
}
|
|
1234
|
+
function removeExpiredState(directory, runtime, justWritten) {
|
|
1235
|
+
const cutoff = runtime.now() - lifetimeMs;
|
|
1236
|
+
for (const file of readdirSync(directory, { withFileTypes: true })) {
|
|
1237
|
+
if (file.name === justWritten || !file.isFile() || !/^[A-Za-z0-9_-]{43}\.json$/.test(file.name)) continue;
|
|
1238
|
+
const path = join3(directory, file.name);
|
|
1239
|
+
const stat2 = pathStat(path);
|
|
1240
|
+
if (stat2?.isFile() && stat2.nlink === 1n && Number(stat2.mtimeMs) <= cutoff) {
|
|
1241
|
+
try {
|
|
1242
|
+
if (runtime.platform === "win32") windowsStateAcl("check-file", path);
|
|
1243
|
+
unlinkSync3(path);
|
|
1244
|
+
} catch {
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function prepareDelivery(kind, scope, target, runtime, upload) {
|
|
1250
|
+
const directory = stateDirectory(runtime, target, true);
|
|
1251
|
+
const requestId = randomBytes(32).toString("base64url");
|
|
1252
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
1253
|
+
const now = runtime.now();
|
|
1254
|
+
const filename = requestId + ".json";
|
|
1255
|
+
const path = join3(directory, filename);
|
|
1256
|
+
const state = JSON.stringify({
|
|
1257
|
+
origin,
|
|
1258
|
+
kind,
|
|
1259
|
+
...scope,
|
|
1260
|
+
requestId,
|
|
1261
|
+
verifier,
|
|
1262
|
+
createdAt: now,
|
|
1263
|
+
expiresAt: now + lifetimeMs,
|
|
1264
|
+
target: target.path,
|
|
1265
|
+
directory: target.directory,
|
|
1266
|
+
upload
|
|
1267
|
+
});
|
|
1268
|
+
if (runtime.platform === "win32") {
|
|
1269
|
+
windowsStateAcl("write-file", path, state);
|
|
1270
|
+
removeExpiredState(directory, runtime, filename);
|
|
1271
|
+
} else {
|
|
1272
|
+
removeExpiredState(directory, runtime);
|
|
1273
|
+
writeConfig({ path, content: null }, state);
|
|
1274
|
+
}
|
|
1275
|
+
const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url");
|
|
1276
|
+
runtime.stdout(JSON.stringify({ request_id: requestId, challenge, ...upload }));
|
|
1277
|
+
}
|
|
1278
|
+
function claimDelivery(kind, input, target, runtime, upload) {
|
|
1279
|
+
const directory = stateDirectory(runtime, target, false);
|
|
1280
|
+
const path = join3(directory, input.requestId + ".json");
|
|
1281
|
+
try {
|
|
1282
|
+
const checked = runtime.platform === "win32" ? pathStat(path) : void 0;
|
|
1283
|
+
if (runtime.platform === "win32") {
|
|
1284
|
+
if (!checked?.isFile() || checked.nlink !== 1n || checked.size > 4096n) {
|
|
1285
|
+
return failDelivery("delivery_state_unavailable");
|
|
1286
|
+
}
|
|
1287
|
+
windowsStateAcl("check-file", path);
|
|
1288
|
+
}
|
|
1289
|
+
return withDestinationLock(path, () => {
|
|
1290
|
+
const stat2 = pathStat(path);
|
|
1291
|
+
if (!stat2?.isFile() || stat2.nlink !== 1n || stat2.size > 4096n || (checked ? !sameOpenFile(checked, stat2) : !privateMode(stat2))) {
|
|
1292
|
+
return failDelivery("delivery_state_unavailable");
|
|
1293
|
+
}
|
|
1294
|
+
const before = snapshot(path);
|
|
1295
|
+
if (before.content === null || stat2.ino !== before.identity.ino || stat2.dev !== before.identity.dev || stat2.birthtimeNs !== before.identity.birthtimeNs) return failDelivery("delivery_state_unavailable");
|
|
1296
|
+
const state = parseConfig("jsonc", before.content);
|
|
1297
|
+
const now = runtime.now();
|
|
1298
|
+
if (state.origin !== origin || state.requestId !== input.requestId || !isBase64Url(state.verifier, 32) || !validUuid(state.merchantId) || !validUuid(state.operationId) || state.environment !== "sandbox" && state.environment !== "production" || typeof state.createdAt !== "number" || typeof state.expiresAt !== "number" || !Number.isSafeInteger(state.createdAt) || !Number.isSafeInteger(state.expiresAt) || state.createdAt > now || state.expiresAt <= state.createdAt || state.expiresAt - state.createdAt > lifetimeMs) {
|
|
1299
|
+
return failDelivery("delivery_state_unavailable");
|
|
1300
|
+
}
|
|
1301
|
+
const consume = () => {
|
|
1302
|
+
if (checked) {
|
|
1303
|
+
const current = pathStat(path);
|
|
1304
|
+
if (!current || !sameOpenFile(stat2, current) || current.nlink !== 1n || current.size !== stat2.size || current.mtimeNs !== stat2.mtimeNs || current.ctimeNs !== stat2.ctimeNs) {
|
|
1305
|
+
return failDelivery("delivery_state_unavailable");
|
|
1306
|
+
}
|
|
1307
|
+
} else assertUnchanged(before);
|
|
1308
|
+
unlinkSync3(path);
|
|
1309
|
+
};
|
|
1310
|
+
if (state.expiresAt <= now) {
|
|
1311
|
+
consume();
|
|
1312
|
+
return failDelivery("delivery_state_unavailable");
|
|
1313
|
+
}
|
|
1314
|
+
if (state.kind !== kind || state.directory !== target.directory || state.target !== target.path || upload && (!object(state.upload) || upload.byte_length !== state.upload.byte_length || upload.content_sha256 !== state.upload.content_sha256 || upload.content_type !== state.upload.content_type) || !upload && state.upload !== void 0) return failDelivery("delivery_context_mismatch");
|
|
1315
|
+
consume();
|
|
1316
|
+
return {
|
|
1317
|
+
requestId: input.requestId,
|
|
1318
|
+
verifier: state.verifier,
|
|
1319
|
+
expiresAt: state.expiresAt,
|
|
1320
|
+
merchantId: state.merchantId,
|
|
1321
|
+
environment: state.environment,
|
|
1322
|
+
operationId: state.operationId
|
|
1323
|
+
};
|
|
1324
|
+
});
|
|
1325
|
+
} catch (cause) {
|
|
1326
|
+
if (cause instanceof MerchantDeliveryError) throw cause;
|
|
1327
|
+
return failDelivery("delivery_state_unavailable");
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function checkDeliveryExpiry(proof, runtime) {
|
|
1331
|
+
if (runtime.now() >= proof.expiresAt) failDelivery("delivery_state_unavailable");
|
|
1332
|
+
}
|
|
1333
|
+
async function redeemDelivery(kind, input, proof, runtime, upload) {
|
|
1334
|
+
checkDeliveryExpiry(proof, runtime);
|
|
1335
|
+
const install = kind === "install-secret";
|
|
1336
|
+
const url = origin + resource + (install ? "/tickets/secret/redeem" : "/files/" + input.ticket);
|
|
1337
|
+
const headers = new Headers({ "Accept-Encoding": "identity", "Cache-Control": "no-store" });
|
|
1338
|
+
let body;
|
|
1339
|
+
if (install) {
|
|
1340
|
+
headers.set("Content-Type", "application/json");
|
|
1341
|
+
body = JSON.stringify({ ticket: input.ticket, request_id: proof.requestId, verifier: proof.verifier });
|
|
1342
|
+
} else {
|
|
1343
|
+
headers.set("Paymos-Delivery-Request", proof.requestId);
|
|
1344
|
+
headers.set("Paymos-Delivery-Verifier", proof.verifier);
|
|
1345
|
+
if (upload) {
|
|
1346
|
+
headers.set("Content-Type", upload.descriptor.content_type);
|
|
1347
|
+
body = upload.bytes;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
let response;
|
|
1351
|
+
try {
|
|
1352
|
+
response = await runtime.fetch(url, {
|
|
1353
|
+
method: kind === "download-file" ? "GET" : "POST",
|
|
1354
|
+
headers,
|
|
1355
|
+
...body === void 0 ? {} : { body },
|
|
1356
|
+
credentials: "omit",
|
|
1357
|
+
redirect: "error",
|
|
1358
|
+
referrerPolicy: "no-referrer",
|
|
1359
|
+
signal: AbortSignal.timeout(Math.max(1, Math.min(requestTimeoutMs, proof.expiresAt - runtime.now())))
|
|
1360
|
+
});
|
|
1361
|
+
} catch {
|
|
1362
|
+
return failDelivery("delivery_request_failed");
|
|
1363
|
+
}
|
|
1364
|
+
if (response.redirected || response.url && response.url !== url || response.status !== (kind === "upload-file" ? 204 : 200)) {
|
|
1365
|
+
void response.body?.cancel().catch(() => {
|
|
1366
|
+
});
|
|
1367
|
+
if (response.status === 413) return failDelivery("delivery_file_too_large");
|
|
1368
|
+
if (response.status === 404 || response.status === 410) return failDelivery("delivery_unavailable");
|
|
1369
|
+
return failDelivery("delivery_request_failed");
|
|
1370
|
+
}
|
|
1371
|
+
return response;
|
|
1372
|
+
}
|
|
1373
|
+
function responseType(response) {
|
|
1374
|
+
return response.headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase();
|
|
1375
|
+
}
|
|
1376
|
+
async function streamDelivery(response, limit, write) {
|
|
1377
|
+
const rawLength = response.headers.get("Content-Length");
|
|
1378
|
+
const encoding = response.headers.get("Content-Encoding");
|
|
1379
|
+
const advertised = rawLength === null || encoding && encoding !== "identity" ? void 0 : Number(rawLength);
|
|
1380
|
+
if (advertised !== void 0 && (!/^\d+$/.test(rawLength) || !Number.isSafeInteger(advertised) || advertised > limit)) return failDelivery("delivery_file_too_large");
|
|
1381
|
+
if (!response.body) return failDelivery("delivery_invalid_response");
|
|
1382
|
+
const reader = response.body.getReader();
|
|
1383
|
+
let bytes = 0;
|
|
1384
|
+
let completed = false;
|
|
1385
|
+
try {
|
|
1386
|
+
while (true) {
|
|
1387
|
+
let next;
|
|
1388
|
+
try {
|
|
1389
|
+
next = await reader.read();
|
|
1390
|
+
} catch {
|
|
1391
|
+
return failDelivery("delivery_request_failed");
|
|
1392
|
+
}
|
|
1393
|
+
if (next.done) break;
|
|
1394
|
+
bytes += next.value.byteLength;
|
|
1395
|
+
if (bytes > limit) failDelivery("delivery_file_too_large");
|
|
1396
|
+
if (advertised !== void 0 && bytes > advertised) failDelivery("delivery_invalid_response");
|
|
1397
|
+
await write(next.value);
|
|
1398
|
+
}
|
|
1399
|
+
if (advertised !== void 0 && bytes !== advertised) failDelivery("delivery_invalid_response");
|
|
1400
|
+
completed = true;
|
|
1401
|
+
return bytes;
|
|
1402
|
+
} finally {
|
|
1403
|
+
if (!completed) void reader.cancel().catch(() => {
|
|
1404
|
+
});
|
|
1405
|
+
reader.releaseLock();
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
var secretKeys = {
|
|
1409
|
+
payment: ["PAYMOS_API_KEY", "PAYMOS_API_SECRET"],
|
|
1410
|
+
payout: ["PAYMOS_PAYOUT_API_KEY", "PAYMOS_PAYOUT_API_SECRET"],
|
|
1411
|
+
webhook: ["PAYMOS_WEBHOOK_SECRET"],
|
|
1412
|
+
invite: ["PAYMOS_INVITE_LINK"]
|
|
1413
|
+
};
|
|
1414
|
+
async function redeemedFields(response, proof) {
|
|
1415
|
+
if (responseType(response) !== "application/json") return failDelivery("delivery_invalid_response");
|
|
1416
|
+
const chunks = [];
|
|
1417
|
+
await streamDelivery(response, 16384, (chunk) => {
|
|
1418
|
+
chunks.push(chunk);
|
|
1419
|
+
});
|
|
1420
|
+
let body;
|
|
1421
|
+
try {
|
|
1422
|
+
body = parseConfig("jsonc", new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
|
|
1423
|
+
} catch {
|
|
1424
|
+
return failDelivery("delivery_invalid_response");
|
|
1425
|
+
}
|
|
1426
|
+
if (body.request_id !== proof.requestId || body.merchant_id !== proof.merchantId || body.environment !== proof.environment || body.operation_id !== proof.operationId) {
|
|
1427
|
+
return failDelivery("delivery_context_mismatch");
|
|
1428
|
+
}
|
|
1429
|
+
const kind = body.kind;
|
|
1430
|
+
if (typeof kind !== "string" || !Object.hasOwn(secretKeys, kind) || !object(body.fields)) {
|
|
1431
|
+
return failDelivery("delivery_invalid_response");
|
|
1432
|
+
}
|
|
1433
|
+
const keys = secretKeys[kind];
|
|
1434
|
+
if (Object.keys(body).length !== 7 || body.suggested_env_key !== keys[0] || Object.keys(body.fields).length !== keys.length) {
|
|
1435
|
+
return failDelivery("delivery_invalid_response");
|
|
1436
|
+
}
|
|
1437
|
+
const fields = {};
|
|
1438
|
+
for (const key of keys) {
|
|
1439
|
+
const value = body.fields[key];
|
|
1440
|
+
if (typeof value !== "string" || value.length === 0 || Buffer.byteLength(value, "utf8") > 4096 || /['\p{Cc}]/u.test(value)) return failDelivery("delivery_invalid_response");
|
|
1441
|
+
fields[key] = value;
|
|
1442
|
+
}
|
|
1443
|
+
return fields;
|
|
1444
|
+
}
|
|
1445
|
+
function mergeEnv(original, fields) {
|
|
1446
|
+
if (original.includes("\uFFFD")) return failDelivery("delivery_local_io_failed");
|
|
1447
|
+
const bom = original.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
1448
|
+
const text = original.slice(bom.length);
|
|
1449
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
1450
|
+
const before = parseEnv(text);
|
|
1451
|
+
const kept = text.split(/(?<=\n)/).filter((line) => {
|
|
1452
|
+
const assignment = /^[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=/.exec(line);
|
|
1453
|
+
if (!assignment || !Object.hasOwn(fields, assignment[1])) return true;
|
|
1454
|
+
const value = line.slice(assignment[0].length).trim();
|
|
1455
|
+
const quote = value[0];
|
|
1456
|
+
if ((quote === "'" || quote === '"' || quote === "`") && value.indexOf(quote, 1) < 0) {
|
|
1457
|
+
failDelivery("delivery_local_io_failed");
|
|
1458
|
+
}
|
|
1459
|
+
return false;
|
|
1460
|
+
}).join("");
|
|
1461
|
+
const lines = Object.entries(fields).map(([key, value]) => key + "='" + value + "'" + eol).join("");
|
|
1462
|
+
const next = kept + (kept === "" || kept.endsWith("\n") ? "" : eol) + lines;
|
|
1463
|
+
const parsed = parseEnv(next);
|
|
1464
|
+
const expected = { ...before, ...fields };
|
|
1465
|
+
if (Object.keys(parsed).length !== Object.keys(expected).length || Object.entries(expected).some(([key, value]) => parsed[key] !== value)) return failDelivery("delivery_local_io_failed");
|
|
1466
|
+
return bom + next;
|
|
1467
|
+
}
|
|
1468
|
+
async function runInstallSecret(argv, runtime) {
|
|
1469
|
+
return safeDelivery(async () => {
|
|
1470
|
+
const input = deliveryArguments(argv, "install-secret");
|
|
1471
|
+
const io = runtime ?? defaultDeliveryRuntime();
|
|
1472
|
+
const target = deliveryTarget(input.file, io);
|
|
1473
|
+
const before = snapshot(target.path);
|
|
1474
|
+
if (input.prepare) {
|
|
1475
|
+
prepareDelivery("install-secret", input.scope, target, io);
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
const proof = claimDelivery("install-secret", input, target, io);
|
|
1479
|
+
const response = await redeemDelivery("install-secret", input, proof, io);
|
|
1480
|
+
const fields = await redeemedFields(response, proof);
|
|
1481
|
+
withDestinationLock(target.path, () => {
|
|
1482
|
+
checkDeliveryExpiry(proof, io);
|
|
1483
|
+
assertDeliveryTarget(target);
|
|
1484
|
+
assertUnchanged(before);
|
|
1485
|
+
writeConfig(before, mergeEnv(before.content ?? "", fields));
|
|
1486
|
+
});
|
|
1487
|
+
io.stdout(JSON.stringify({ status: "installed" }));
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
// src/files.ts
|
|
1492
|
+
var maxUploadBytes = 2 * 1024 * 1024;
|
|
1493
|
+
var maxDownloadBytes = 128 * 1024 * 1024;
|
|
1494
|
+
var exportTypes = /* @__PURE__ */ new Set([
|
|
1495
|
+
"text/csv",
|
|
1496
|
+
"application/zip",
|
|
1497
|
+
"application/x-zip-compressed",
|
|
1498
|
+
"application/octet-stream",
|
|
1499
|
+
"image/png",
|
|
1500
|
+
"image/svg+xml"
|
|
1501
|
+
]);
|
|
1502
|
+
function imageType(bytes) {
|
|
1503
|
+
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
|
|
1504
|
+
if (bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255]))) return "image/jpeg";
|
|
1505
|
+
if (bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
|
|
1506
|
+
return failDelivery("delivery_context_mismatch");
|
|
1507
|
+
}
|
|
1508
|
+
function readUpload(target) {
|
|
1509
|
+
const stat2 = assertDeliveryTarget(target);
|
|
1510
|
+
if (!stat2 || stat2.size <= 0n) return failDelivery("delivery_unsafe_path");
|
|
1511
|
+
if (stat2.size > BigInt(maxUploadBytes)) return failDelivery("delivery_file_too_large");
|
|
1512
|
+
const fd = openSync4(target.path, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
|
|
1513
|
+
try {
|
|
1514
|
+
const opened = fstatSync4(fd, { bigint: true });
|
|
1515
|
+
if (!sameOpenFile(stat2, opened) || opened.size !== stat2.size) return failDelivery("delivery_context_mismatch");
|
|
1516
|
+
const bytes = Buffer.alloc(Number(stat2.size));
|
|
1517
|
+
let offset = 0;
|
|
1518
|
+
while (offset < bytes.length) {
|
|
1519
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, null);
|
|
1520
|
+
if (!count) return failDelivery("delivery_context_mismatch");
|
|
1521
|
+
offset += count;
|
|
1522
|
+
}
|
|
1523
|
+
const after = assertDeliveryTarget(target);
|
|
1524
|
+
if (readSync(fd, Buffer.alloc(1), 0, 1, null) !== 0 || !after || !sameOpenFile(after, opened) || after.mtimeNs !== stat2.mtimeNs || after.size !== stat2.size) return failDelivery("delivery_context_mismatch");
|
|
1525
|
+
return { bytes, descriptor: {
|
|
1526
|
+
byte_length: bytes.length,
|
|
1527
|
+
content_sha256: createHash2("sha256").update(bytes).digest("hex"),
|
|
1528
|
+
content_type: imageType(bytes)
|
|
1529
|
+
} };
|
|
1530
|
+
} finally {
|
|
1531
|
+
closeSync4(fd);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
async function runUploadFile(argv, runtime) {
|
|
1535
|
+
return safeDelivery(async () => {
|
|
1536
|
+
const input = deliveryArguments(argv, "upload-file");
|
|
1537
|
+
const io = runtime ?? defaultDeliveryRuntime();
|
|
1538
|
+
const target = deliveryTarget(input.file, io);
|
|
1539
|
+
const upload = readUpload(target);
|
|
1540
|
+
if (input.prepare) {
|
|
1541
|
+
prepareDelivery("upload-file", input.scope, target, io, upload.descriptor);
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
const proof = claimDelivery("upload-file", input, target, io, upload.descriptor);
|
|
1545
|
+
await redeemDelivery("upload-file", input, proof, io, upload);
|
|
1546
|
+
io.stdout(JSON.stringify({ status: "staged" }));
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
async function runDownloadFile(argv, runtime) {
|
|
1550
|
+
return safeDelivery(async () => {
|
|
1551
|
+
const input = deliveryArguments(argv, "download-file");
|
|
1552
|
+
const io = runtime ?? defaultDeliveryRuntime();
|
|
1553
|
+
const target = deliveryTarget(input.file, io);
|
|
1554
|
+
if (assertDeliveryTarget(target)) failDelivery("delivery_unsafe_path");
|
|
1555
|
+
if (input.prepare) {
|
|
1556
|
+
prepareDelivery("download-file", input.scope, target, io);
|
|
1557
|
+
return;
|
|
1558
|
+
}
|
|
1559
|
+
const proof = claimDelivery("download-file", input, target, io);
|
|
1560
|
+
const temp = join4(dirname4(target.path), ".paymos-download-" + randomUUID2() + ".tmp");
|
|
1561
|
+
const file = await open(temp, "wx", 384);
|
|
1562
|
+
let identity;
|
|
1563
|
+
let closed = false;
|
|
1564
|
+
try {
|
|
1565
|
+
identity = await file.stat({ bigint: true });
|
|
1566
|
+
if (process.platform !== "win32") await file.chmod(384);
|
|
1567
|
+
const response = await redeemDelivery("download-file", input, proof, io);
|
|
1568
|
+
if (!exportTypes.has(responseType(response) ?? "")) {
|
|
1569
|
+
void response.body?.cancel().catch(() => {
|
|
1570
|
+
});
|
|
1571
|
+
failDelivery("delivery_invalid_response");
|
|
1572
|
+
}
|
|
1573
|
+
const bytes = await streamDelivery(response, maxDownloadBytes, (chunk) => file.writeFile(chunk));
|
|
1574
|
+
await file.sync();
|
|
1575
|
+
await file.close();
|
|
1576
|
+
closed = true;
|
|
1577
|
+
withDestinationLock(target.path, () => {
|
|
1578
|
+
checkDeliveryExpiry(proof, io);
|
|
1579
|
+
if (assertDeliveryTarget(target)) failDelivery("delivery_unsafe_path");
|
|
1580
|
+
const staged = lstatSync6(temp, { bigint: true });
|
|
1581
|
+
if (!sameOpenFile(staged, identity) || staged.size !== BigInt(bytes)) failDelivery("delivery_context_mismatch");
|
|
1582
|
+
linkSync2(temp, target.path);
|
|
1583
|
+
});
|
|
1584
|
+
io.stdout(JSON.stringify({ status: "downloaded", byte_length: bytes }));
|
|
1585
|
+
} finally {
|
|
1586
|
+
if (!closed) await file.close().catch(() => {
|
|
1587
|
+
});
|
|
1588
|
+
try {
|
|
1589
|
+
if (identity && sameOpenFile(lstatSync6(temp, { bigint: true }), identity)) unlinkSync4(temp);
|
|
1590
|
+
} catch {
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
// src/gateway.ts
|
|
1597
|
+
import { Paymos } from "@paymos/sdk";
|
|
1598
|
+
|
|
1599
|
+
// src/errors.ts
|
|
1600
|
+
import { ApiError } from "@paymos/sdk";
|
|
1601
|
+
var ToolError = class extends Error {
|
|
1602
|
+
code;
|
|
1603
|
+
constructor(code, message) {
|
|
1604
|
+
super(message);
|
|
1605
|
+
this.name = "ToolError";
|
|
1606
|
+
this.code = code;
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
function toolErrorFrom(error2) {
|
|
1610
|
+
if (error2 instanceof ToolError) return error2;
|
|
1611
|
+
if (error2 instanceof ApiError) {
|
|
1612
|
+
const code = error2.code === "" ? "api_error" : error2.code;
|
|
1613
|
+
return new ToolError(`paymos/${code}`, error2.message);
|
|
1614
|
+
}
|
|
1615
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
1616
|
+
return new ToolError("paymos/sdk_error", message);
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// src/gateway.ts
|
|
1620
|
+
var PaymosGateway = class {
|
|
1621
|
+
credentials;
|
|
1622
|
+
overrides;
|
|
1623
|
+
constructor(credentials, overrides = {}) {
|
|
1624
|
+
this.credentials = credentials;
|
|
1625
|
+
this.overrides = overrides;
|
|
1626
|
+
}
|
|
1627
|
+
check() {
|
|
1628
|
+
return checkCredentials(this.credentials);
|
|
1629
|
+
}
|
|
1630
|
+
/** Webhook signing secret for the local `verify_webhook_signature` tool. */
|
|
1631
|
+
webhookSecret() {
|
|
1632
|
+
return this.credentials.webhookSecret;
|
|
1633
|
+
}
|
|
1634
|
+
client() {
|
|
1635
|
+
const check = this.check();
|
|
1636
|
+
if (!check.ok) throw new ToolError(check.code, check.message);
|
|
1637
|
+
return new Paymos({
|
|
1638
|
+
apiKey: this.credentials.apiKeyId,
|
|
1639
|
+
apiSecret: this.credentials.apiSecret,
|
|
1640
|
+
...this.overrides.fetch ? { fetch: this.overrides.fetch } : {}
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
invoices() {
|
|
1644
|
+
return this.client().invoices;
|
|
1645
|
+
}
|
|
1646
|
+
paymentChannels() {
|
|
1647
|
+
return this.client().paymentChannels;
|
|
1648
|
+
}
|
|
1649
|
+
paymentChannelDeposits() {
|
|
1650
|
+
return this.client().paymentChannelDeposits;
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
|
|
1654
|
+
// src/server.ts
|
|
1655
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1656
|
+
|
|
1657
|
+
// src/tools.ts
|
|
1658
|
+
import { z } from "zod";
|
|
1659
|
+
import { TimestampSkewError, WebhookVerifier } from "@paymos/sdk";
|
|
1660
|
+
|
|
1661
|
+
// src/wire-shape.ts
|
|
1662
|
+
function toWireShape(value) {
|
|
1663
|
+
if (Array.isArray(value)) return value.map(toWireShape);
|
|
1664
|
+
if (value === null || typeof value !== "object") return value;
|
|
1665
|
+
const out = {};
|
|
1666
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1667
|
+
out[key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)] = toWireShape(item);
|
|
1668
|
+
}
|
|
1669
|
+
return out;
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
// src/tools.ts
|
|
1673
|
+
var NETWORKS = "TRC20, ERC20, BEP20, POLYGON, ARBITRUM, OPTIMISM, BASE, TON, AVAX, SOL, NEAR, SUI, PLASMA";
|
|
1674
|
+
var INVOICE_STATUSES = [
|
|
1675
|
+
"awaiting_client",
|
|
1676
|
+
"awaiting_payment",
|
|
1677
|
+
"confirming",
|
|
1678
|
+
"underpaid_waiting",
|
|
1679
|
+
"paid",
|
|
1680
|
+
"paid_over",
|
|
1681
|
+
"underpaid",
|
|
1682
|
+
"expired",
|
|
1683
|
+
"cancelled"
|
|
1684
|
+
];
|
|
1685
|
+
var INVOICE_RESULT_HINT = "Returns the invoice in wire form: invoice_id, status, payment_url, order, payment (expected, address, transfers), expires_at. status: awaiting_client | awaiting_payment | confirming | underpaid_waiting | paid | paid_over | underpaid | expired | cancelled.";
|
|
1686
|
+
function textJson(value) {
|
|
1687
|
+
return {
|
|
1688
|
+
content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
function failure(error2) {
|
|
1692
|
+
const toolError = toolErrorFrom(error2);
|
|
1693
|
+
return {
|
|
1694
|
+
isError: true,
|
|
1695
|
+
content: [{ type: "text", text: JSON.stringify({ code: toolError.code, message: toolError.message }, null, 2) }]
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
async function guarded(run) {
|
|
1699
|
+
try {
|
|
1700
|
+
return await run();
|
|
1701
|
+
} catch (error2) {
|
|
1702
|
+
return failure(error2);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
function registerTools(server, gateway) {
|
|
1706
|
+
server.registerTool(
|
|
1707
|
+
"create_payment_channel",
|
|
1708
|
+
{
|
|
1709
|
+
title: "Create payment channel",
|
|
1710
|
+
description: "Create a Sandbox payment channel using project_id and external_id. Repeating the same pair returns the existing channel.",
|
|
1711
|
+
inputSchema: {
|
|
1712
|
+
project_id: z.string().min(1).describe("Project ID."),
|
|
1713
|
+
external_id: z.string().min(1).max(128).describe("Your identifier for the payer; channel creation is idempotent within the project.")
|
|
1714
|
+
}
|
|
1715
|
+
},
|
|
1716
|
+
async ({ project_id, external_id }) => guarded(async () => {
|
|
1717
|
+
const channel = await gateway.paymentChannels().create({ projectId: project_id, externalId: external_id });
|
|
1718
|
+
return textJson(toWireShape(channel));
|
|
1719
|
+
})
|
|
1720
|
+
);
|
|
1721
|
+
server.registerTool(
|
|
1722
|
+
"get_payment_channel",
|
|
1723
|
+
{
|
|
1724
|
+
title: "Get payment channel",
|
|
1725
|
+
description: "Read a Sandbox payment channel by ID, including its current status and available deposit addresses.",
|
|
1726
|
+
inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
|
|
1727
|
+
},
|
|
1728
|
+
async ({ payment_channel_id }) => guarded(async () => textJson(toWireShape(await gateway.paymentChannels().get(payment_channel_id))))
|
|
1729
|
+
);
|
|
1730
|
+
server.registerTool(
|
|
1731
|
+
"list_payment_channels",
|
|
1732
|
+
{
|
|
1733
|
+
title: "List payment channels",
|
|
1734
|
+
description: "List Sandbox payment channels with optional project_id, external_id, and status filters. Use limit and cursor to request one page at a time.",
|
|
1735
|
+
inputSchema: {
|
|
1736
|
+
project_id: z.string().min(1).optional().describe("Project ID."),
|
|
1737
|
+
external_id: z.string().min(1).max(128).optional().describe("Your identifier for the payer; channel creation is idempotent within the project."),
|
|
1738
|
+
status: z.array(z.enum(["active", "blocked", "provisioning"])).optional().describe("Array of channel statuses to include: active, blocked, or provisioning."),
|
|
1739
|
+
limit: z.number().int().min(1).max(100).optional().describe("Maximum number of items to return in this page."),
|
|
1740
|
+
cursor: z.string().optional().describe("Pagination cursor from the previous channel-list response.")
|
|
1741
|
+
}
|
|
1742
|
+
},
|
|
1743
|
+
async ({ project_id, external_id, status, limit, cursor }) => guarded(async () => {
|
|
1744
|
+
const page = await gateway.paymentChannels().list({
|
|
1745
|
+
...project_id !== void 0 ? { projectId: project_id } : {},
|
|
1746
|
+
...external_id !== void 0 ? { externalId: external_id } : {},
|
|
1747
|
+
...status !== void 0 ? { status } : {},
|
|
1748
|
+
...limit !== void 0 ? { limit } : {},
|
|
1749
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
1750
|
+
});
|
|
1751
|
+
return textJson(toWireShape(page));
|
|
1752
|
+
})
|
|
1753
|
+
);
|
|
1754
|
+
server.registerTool(
|
|
1755
|
+
"block_payment_channel",
|
|
1756
|
+
{
|
|
1757
|
+
title: "Block payment channel",
|
|
311
1758
|
description: "Set a Sandbox payment channel's status to blocked.",
|
|
312
1759
|
inputSchema: { payment_channel_id: z.string().min(1).describe("Payment channel ID.") }
|
|
313
1760
|
},
|
|
@@ -1151,446 +2598,147 @@ verifier, and a release ships only once its own tests run against that suite.</p
|
|
|
1151
2598
|
another keeps its signing, paging, retry and webhook semantics. Two SDKs building
|
|
1152
2599
|
the same filtered list request sign identical bytes.</p>
|
|
1153
2600
|
<h2 id="what-php-adds">What PHP adds</h2>
|
|
1154
|
-
<p>The PHP SDK carries a plugin-integration layer that exists in no other client:
|
|
1155
|
-
reverse verification of a webhook against a fresh read of the API, an amount and
|
|
1156
|
-
currency guard before an order is released, replay deduplication behind a
|
|
1157
|
-
pluggable event store, a verifier that holds the Sandbox and Live secrets at
|
|
1158
|
-
once, a reconciler, a mapper from event to order action, and encrypted credential
|
|
1159
|
-
storage.</p>
|
|
1160
|
-
<p>That layer is why the CMS plugins are thin \u2014 the order-state logic sits once in
|
|
1161
|
-
the SDK underneath them instead of eight times above it. None of it applies to
|
|
1162
|
-
the other seven: they are client, signing, resources, pagination and webhook
|
|
1163
|
-
verification, and building on more than that will find nothing there.</p>
|
|
1164
|
-
<h2 id="security-rules">Security rules</h2>
|
|
1165
|
-
<div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>These SDKs are server-side only. Never put an API secret in browser JavaScript,
|
|
1166
|
-
a mobile application, a public repository, a URL, or a log.</p></div></div>
|
|
1167
|
-
<p>Request authentication and webhook authentication use different signatures.
|
|
1168
|
-
API requests use base64 HMAC-SHA256 over the canonical request. Webhooks use a
|
|
1169
|
-
hex HMAC-SHA256 over <code>{timestamp}.{exact raw body}</code>. Pass the unparsed request
|
|
1170
|
-
bytes to the SDK verifier before decoding JSON. The verifier refuses a timestamp
|
|
1171
|
-
more than five minutes away from now by default, and accepts a header carrying
|
|
1172
|
-
two <code>v1</code> values, so a <a href="/docs/webhooks/verify">secret rotation</a> costs you no code
|
|
1173
|
-
change.</p>
|
|
1174
|
-
<p>For endpoint schemas and examples, continue with <a href="/docs/authentication">Authentication</a>,
|
|
1175
|
-
<a href="/docs/invoices/create">Invoices</a>, <a href="/docs/withdrawals/create">Withdrawals</a>,
|
|
1176
|
-
<a href="/docs/balances/get">Balances</a>, and <a href="/docs/webhooks">Webhooks</a>.</p>`
|
|
1177
|
-
}
|
|
1178
|
-
];
|
|
1179
|
-
|
|
1180
|
-
// src/resources.ts
|
|
1181
|
-
function registerResources(server) {
|
|
1182
|
-
for (const resource of DOC_RESOURCES) {
|
|
1183
|
-
server.registerResource(
|
|
1184
|
-
resource.name,
|
|
1185
|
-
resource.uri,
|
|
1186
|
-
{ description: resource.description, mimeType: resource.mimeType },
|
|
1187
|
-
async (uri) => ({
|
|
1188
|
-
contents: [{ uri: uri.href, mimeType: resource.mimeType, text: resource.text }]
|
|
1189
|
-
})
|
|
1190
|
-
);
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
// src/integration-recommendation.ts
|
|
1195
|
-
import { z as z2 } from "zod";
|
|
1196
|
-
var INTEGRATION_INSTRUCTIONS = "When helping a developer choose a payment integration, call recommend_payment_integration with scenario order_checkout, repeat_deposits, both, or unsure. Respect the merchant\u2019s stated preference; do not replace an explicit choice. Explain why the recommended flow fits their needs and identify missing information. Use unsure when the need is unclear; ask whether the customer will pay for each order, repeatedly top up an account, or do both. This MCP server calls sandbox only and rejects live and payout credentials. Check availability in the target environment.";
|
|
1197
|
-
var GUIDE = `Choose the flow before creating a payment resource.
|
|
1198
|
-
|
|
1199
|
-
Use an invoice when your customer pays for a specific order. An invoice has a set amount, an expiry, and payment statuses; its hosted checkout gives the customer a page to pay that invoice.
|
|
1200
|
-
|
|
1201
|
-
Choose a payment channel for repeated customer deposits. It belongs to one payer and keeps a permanent address per supported network. The channel sets no amount or expiry and has no terminal payment status. Each credited transfer becomes a separate deposit, so track deposits individually when crediting the customer\u2019s account. Transfers below the minimum deposit are not credited or returned.
|
|
1202
|
-
|
|
1203
|
-
You can use both in the same integration. For example, use invoices for purchases and a payment channel for account top-ups. If the intended flow is unclear, ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D
|
|
1204
|
-
|
|
1205
|
-
Test the chosen flow in sandbox. This MCP server calls sandbox only and rejects live and payout credentials. Create sandbox and production channels separately, and check availability in the target environment. Sandbox addresses are synthetic; each deposit simulation creates a new test deposit rather than updating an earlier simulation.
|
|
1206
|
-
|
|
1207
|
-
Credit channel deposits only after confirmation. Verify webhook signatures and require \`confirmed\` with \`is_final\` before crediting a deposit. Webhooks can repeat or arrive out of order: deduplicate deliveries by \`event_id\` and prevent duplicate credit for the same deposit.
|
|
1208
|
-
|
|
1209
|
-
Use the confirmed-deposit feed to reconcile deposits. Save every returned \`next_cursor\`, even on empty pages, and inspect \`blocked\` when present. \`confirmed_from\` bounds the first poll and forms part of the cursor\u2019s fingerprint; keep its value unchanged when continuing with that cursor. Feed cursors expire 24 hours after issue, so poll at least daily. If a cursor expires, restart with a bounded \`confirmed_from\` and retain deposit deduplication.
|
|
1210
|
-
|
|
1211
|
-
Start with the flow you chose. The recommendation needs no credentials; API calls need test credentials.
|
|
1212
|
-
|
|
1213
|
-
For invoices, call \`create_invoice\` with \`project_id\`, \`external_order_id\`, \`amount\` as a decimal string, and \`currency\`. Save the invoice\u2019s link to your order, and use the returned \`payment_url\` for checkout. Test a payment with \`simulate_invoice_payment\`, passing \`invoice_id\` and \`stage\`.
|
|
1214
|
-
|
|
1215
|
-
For payment channels, call \`create_payment_channel\` with \`project_id\` and your customer\u2019s \`external_id\`. Save the channel\u2019s link to that customer. Check the returned networks and addresses; an address may still be provisioning. Call \`get_payment_channel\` again to check readiness and addresses. Call \`simulate_payment_channel_deposit\` with \`payment_channel_id\`, \`amount\` as a decimal string, \`currency\`, and \`network\`; \`stage\` is optional. Read any deposit status with \`get_payment_channel_deposit\`, or use \`list_payment_channel_deposits\` for the confirmed-deposit feed.
|
|
1216
|
-
|
|
1217
|
-
If you chose both, follow both paths. Before changing an order or customer balance, verify webhook signatures, apply the flow\u2019s confirmation checks, and deduplicate events. Credit channel deposits only when \`confirmed\` and \`is_final\`.`;
|
|
1218
|
-
var RECOMMENDATIONS = {
|
|
1219
|
-
order_checkout: {
|
|
1220
|
-
recommendation: "invoice",
|
|
1221
|
-
summary: "Use an invoice for each order: it has a set amount, an expiry, payment statuses, and hosted checkout. Explain how this fits the order flow while respecting the merchant\u2019s stated preference."
|
|
1222
|
-
},
|
|
1223
|
-
repeat_deposits: {
|
|
1224
|
-
recommendation: "payment_channel",
|
|
1225
|
-
summary: "Use a payment channel for repeated deposits from one payer to reusable addresses per network. Track credited deposits separately; transfers below the minimum are not credited or returned. The channel sets no amount or expiry."
|
|
1226
|
-
},
|
|
1227
|
-
both: {
|
|
1228
|
-
recommendation: "both",
|
|
1229
|
-
summary: "Use invoices for individual orders and payment channels for repeated account top-ups. Explain which customer action uses each flow, and respect any preference the merchant has already stated."
|
|
1230
|
-
},
|
|
1231
|
-
unsure: {
|
|
1232
|
-
recommendation: "unsure",
|
|
1233
|
-
summary: "Do not choose a flow yet. Ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D Use the answer and the merchant\u2019s preferences to guide the recommendation."
|
|
1234
|
-
}
|
|
1235
|
-
};
|
|
1236
|
-
function registerIntegrationRecommendation(server) {
|
|
1237
|
-
server.registerTool(
|
|
1238
|
-
"recommend_payment_integration",
|
|
1239
|
-
{
|
|
1240
|
-
title: "Recommend a payment integration",
|
|
1241
|
-
description: "Recommend invoices, payment channels, or both from the merchant\u2019s payment flow. Explain the fit and relevant lifecycle. When information is missing, return a targeted question instead of choosing. Respect an explicit merchant choice.",
|
|
1242
|
-
inputSchema: {
|
|
1243
|
-
scenario: z2.enum(["order_checkout", "repeat_deposits", "both", "unsure"]).optional().describe("Choose order_checkout for payment per order, repeat_deposits for repeated customer account top-ups, or both when both flows are needed. Use unsure when the payment flow is unclear; ask whether the customer pays for each order, repeatedly tops up an account, or does both. Respect the merchant\u2019s explicit choice.")
|
|
1244
|
-
},
|
|
1245
|
-
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
|
|
1246
|
-
},
|
|
1247
|
-
async ({ scenario }) => {
|
|
1248
|
-
const selected = scenario ?? "unsure";
|
|
1249
|
-
return {
|
|
1250
|
-
content: [{
|
|
1251
|
-
type: "text",
|
|
1252
|
-
text: JSON.stringify({ scenario: selected, ...RECOMMENDATIONS[selected], guide: GUIDE }, null, 2)
|
|
1253
|
-
}]
|
|
1254
|
-
};
|
|
1255
|
-
}
|
|
1256
|
-
);
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
// src/version.ts
|
|
1260
|
-
var MCP_VERSION = "1.5.0";
|
|
1261
|
-
|
|
1262
|
-
// src/server.ts
|
|
1263
|
-
function buildServer(gateway) {
|
|
1264
|
-
const server = new McpServer(
|
|
1265
|
-
{ name: "paymos", version: MCP_VERSION },
|
|
1266
|
-
{ instructions: INTEGRATION_INSTRUCTIONS }
|
|
1267
|
-
);
|
|
1268
|
-
registerTools(server, gateway);
|
|
1269
|
-
registerIntegrationRecommendation(server);
|
|
1270
|
-
registerResources(server);
|
|
1271
|
-
return server;
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
// src/setup.ts
|
|
1275
|
-
import {
|
|
1276
|
-
chmodSync,
|
|
1277
|
-
closeSync as closeSync2,
|
|
1278
|
-
constants as constants2,
|
|
1279
|
-
existsSync,
|
|
1280
|
-
fstatSync as fstatSync2,
|
|
1281
|
-
linkSync,
|
|
1282
|
-
lstatSync as lstatSync2,
|
|
1283
|
-
mkdirSync,
|
|
1284
|
-
openSync as openSync2,
|
|
1285
|
-
readFileSync as readFileSync2,
|
|
1286
|
-
renameSync,
|
|
1287
|
-
unlinkSync,
|
|
1288
|
-
writeFileSync
|
|
1289
|
-
} from "fs";
|
|
1290
|
-
import { randomUUID } from "crypto";
|
|
1291
|
-
import { homedir } from "os";
|
|
1292
|
-
import { dirname, isAbsolute, join, resolve } from "path";
|
|
1293
|
-
import { createInterface } from "readline";
|
|
1294
|
-
import { Writable } from "stream";
|
|
1295
|
-
import { isDeepStrictEqual } from "util";
|
|
1296
|
-
import { applyEdits, modify, parse as parseJson, parseTree } from "jsonc-parser";
|
|
1297
|
-
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
|
1298
|
-
var SETUP_CLIENTS = [
|
|
1299
|
-
"codex",
|
|
1300
|
-
"claude-code",
|
|
1301
|
-
"claude-desktop",
|
|
1302
|
-
"kimi",
|
|
1303
|
-
"cursor",
|
|
1304
|
-
"windsurf",
|
|
1305
|
-
"opencode",
|
|
1306
|
-
"vscode",
|
|
1307
|
-
"generic"
|
|
1308
|
-
];
|
|
1309
|
-
function error(kind) {
|
|
1310
|
-
throw new Error(SETUP_COPY.errors[kind]);
|
|
1311
|
-
}
|
|
1312
|
-
function options(argv) {
|
|
1313
|
-
const result = { dryRun: false, help: false };
|
|
1314
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1315
|
-
const flags = /* @__PURE__ */ new Map([
|
|
1316
|
-
["--client", "client"],
|
|
1317
|
-
["--config", "config"],
|
|
1318
|
-
["--credentials-file", "credentialsFile"]
|
|
1319
|
-
]);
|
|
1320
|
-
for (let i = 0; i < argv.length; i++) {
|
|
1321
|
-
const arg = argv[i];
|
|
1322
|
-
const split = arg.indexOf("=");
|
|
1323
|
-
const flag = split < 0 ? arg : arg.slice(0, split);
|
|
1324
|
-
const normalized = flag === "-h" ? "--help" : flag;
|
|
1325
|
-
if (seen.has(normalized)) error("arguments");
|
|
1326
|
-
seen.add(normalized);
|
|
1327
|
-
if (normalized === "--help" || normalized === "--dry-run") {
|
|
1328
|
-
if (split >= 0) error("arguments");
|
|
1329
|
-
if (normalized === "--help") result.help = true;
|
|
1330
|
-
else result.dryRun = true;
|
|
1331
|
-
continue;
|
|
1332
|
-
}
|
|
1333
|
-
const field = flags.get(flag);
|
|
1334
|
-
if (!field) error("arguments");
|
|
1335
|
-
const value = split < 0 ? argv[++i] : arg.slice(split + 1);
|
|
1336
|
-
if (value === void 0 || value.trim() === "" || value.startsWith("--")) error("arguments");
|
|
1337
|
-
result[field] = value;
|
|
1338
|
-
}
|
|
1339
|
-
return result;
|
|
1340
|
-
}
|
|
1341
|
-
function object(value) {
|
|
1342
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1343
|
-
}
|
|
1344
|
-
function equalData(left, right) {
|
|
1345
|
-
if (isDeepStrictEqual(left, right)) return true;
|
|
1346
|
-
if (!object(left) || !object(right)) return false;
|
|
1347
|
-
const plain = (value) => Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype;
|
|
1348
|
-
if (!plain(left) || !plain(right)) return false;
|
|
1349
|
-
const keys = Object.keys(left);
|
|
1350
|
-
return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalData(left[key], right[key]));
|
|
1351
|
-
}
|
|
1352
|
-
function absolute(path, context) {
|
|
1353
|
-
if (path === "~") return context.home;
|
|
1354
|
-
if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(context.home, path.slice(2));
|
|
1355
|
-
return resolve(context.cwd, path);
|
|
1356
|
-
}
|
|
1357
|
-
function defaultConfigPath(client, env, context) {
|
|
1358
|
-
const configHome = env.XDG_CONFIG_HOME || join(context.home, ".config");
|
|
1359
|
-
switch (client) {
|
|
1360
|
-
case "codex":
|
|
1361
|
-
return join(env.CODEX_HOME || join(context.home, ".codex"), "config.toml");
|
|
1362
|
-
case "claude-code":
|
|
1363
|
-
return join(context.home, ".claude.json");
|
|
1364
|
-
case "kimi":
|
|
1365
|
-
return join(env.KIMI_CODE_HOME || join(context.home, ".kimi-code"), "mcp.json");
|
|
1366
|
-
case "cursor":
|
|
1367
|
-
return join(context.home, ".cursor", "mcp.json");
|
|
1368
|
-
case "windsurf":
|
|
1369
|
-
return join(context.home, ".codeium", "windsurf", "mcp_config.json");
|
|
1370
|
-
case "vscode":
|
|
1371
|
-
return join(context.cwd, ".vscode", "mcp.json");
|
|
1372
|
-
case "opencode": {
|
|
1373
|
-
if (env.OPENCODE_CONFIG) return env.OPENCODE_CONFIG;
|
|
1374
|
-
const jsonc = join(configHome, "opencode", "opencode.jsonc");
|
|
1375
|
-
return existsSync(jsonc) ? jsonc : join(configHome, "opencode", "opencode.json");
|
|
1376
|
-
}
|
|
1377
|
-
case "claude-desktop":
|
|
1378
|
-
if (context.platform === "win32" && env.APPDATA)
|
|
1379
|
-
return join(env.APPDATA, "Claude", "claude_desktop_config.json");
|
|
1380
|
-
if (context.platform === "darwin")
|
|
1381
|
-
return join(context.home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
1382
|
-
return error("configRequired");
|
|
1383
|
-
case "generic":
|
|
1384
|
-
return error("configRequired");
|
|
2601
|
+
<p>The PHP SDK carries a plugin-integration layer that exists in no other client:
|
|
2602
|
+
reverse verification of a webhook against a fresh read of the API, an amount and
|
|
2603
|
+
currency guard before an order is released, replay deduplication behind a
|
|
2604
|
+
pluggable event store, a verifier that holds the Sandbox and Live secrets at
|
|
2605
|
+
once, a reconciler, a mapper from event to order action, and encrypted credential
|
|
2606
|
+
storage.</p>
|
|
2607
|
+
<p>That layer is why the CMS plugins are thin \u2014 the order-state logic sits once in
|
|
2608
|
+
the SDK underneath them instead of eight times above it. None of it applies to
|
|
2609
|
+
the other seven: they are client, signing, resources, pagination and webhook
|
|
2610
|
+
verification, and building on more than that will find nothing there.</p>
|
|
2611
|
+
<h2 id="security-rules">Security rules</h2>
|
|
2612
|
+
<div class="callout callout--warning"><svg class="callout__icon" viewBox="0 0 20 20" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M10 3 1.7 17h16.6L10 3Zm0 5v4m0 3h.01"></path></svg><div class="callout__body"><p>These SDKs are server-side only. Never put an API secret in browser JavaScript,
|
|
2613
|
+
a mobile application, a public repository, a URL, or a log.</p></div></div>
|
|
2614
|
+
<p>Request authentication and webhook authentication use different signatures.
|
|
2615
|
+
API requests use base64 HMAC-SHA256 over the canonical request. Webhooks use a
|
|
2616
|
+
hex HMAC-SHA256 over <code>{timestamp}.{exact raw body}</code>. Pass the unparsed request
|
|
2617
|
+
bytes to the SDK verifier before decoding JSON. The verifier refuses a timestamp
|
|
2618
|
+
more than five minutes away from now by default, and accepts a header carrying
|
|
2619
|
+
two <code>v1</code> values, so a <a href="/docs/webhooks/verify">secret rotation</a> costs you no code
|
|
2620
|
+
change.</p>
|
|
2621
|
+
<p>For endpoint schemas and examples, continue with <a href="/docs/authentication">Authentication</a>,
|
|
2622
|
+
<a href="/docs/invoices/create">Invoices</a>, <a href="/docs/withdrawals/create">Withdrawals</a>,
|
|
2623
|
+
<a href="/docs/balances/get">Balances</a>, and <a href="/docs/webhooks">Webhooks</a>.</p>`
|
|
1385
2624
|
}
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
return error("configFile");
|
|
1400
|
-
} finally {
|
|
1401
|
-
if (fd !== void 0) closeSync2(fd);
|
|
2625
|
+
];
|
|
2626
|
+
|
|
2627
|
+
// src/resources.ts
|
|
2628
|
+
function registerResources(server) {
|
|
2629
|
+
for (const resource2 of DOC_RESOURCES) {
|
|
2630
|
+
server.registerResource(
|
|
2631
|
+
resource2.name,
|
|
2632
|
+
resource2.uri,
|
|
2633
|
+
{ description: resource2.description, mimeType: resource2.mimeType },
|
|
2634
|
+
async (uri) => ({
|
|
2635
|
+
contents: [{ uri: uri.href, mimeType: resource2.mimeType, text: resource2.text }]
|
|
2636
|
+
})
|
|
2637
|
+
);
|
|
1402
2638
|
}
|
|
1403
2639
|
}
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
}
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
2640
|
+
|
|
2641
|
+
// src/integration-recommendation.ts
|
|
2642
|
+
import { z as z2 } from "zod";
|
|
2643
|
+
var INTEGRATION_INSTRUCTIONS = "When helping a developer choose a payment integration, call recommend_payment_integration with scenario order_checkout, repeat_deposits, both, or unsure. Respect the merchant\u2019s stated preference; do not replace an explicit choice. Explain why the recommended flow fits their needs and identify missing information. Use unsure when the need is unclear; ask whether the customer will pay for each order, repeatedly top up an account, or do both. This MCP server calls sandbox only and rejects live and payout credentials. Check availability in the target environment.";
|
|
2644
|
+
var GUIDE = `Choose the flow before creating a payment resource.
|
|
2645
|
+
|
|
2646
|
+
Use an invoice when your customer pays for a specific order. An invoice has a set amount, an expiry, and payment statuses; its hosted checkout gives the customer a page to pay that invoice.
|
|
2647
|
+
|
|
2648
|
+
Choose a payment channel for repeated customer deposits. It belongs to one payer and keeps a permanent address per supported network. The channel sets no amount or expiry and has no terminal payment status. Each credited transfer becomes a separate deposit, so track deposits individually when crediting the customer\u2019s account. Transfers below the minimum deposit are not credited or returned.
|
|
2649
|
+
|
|
2650
|
+
You can use both in the same integration. For example, use invoices for purchases and a payment channel for account top-ups. If the intended flow is unclear, ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D
|
|
2651
|
+
|
|
2652
|
+
Test the chosen flow in sandbox. This MCP server calls sandbox only and rejects live and payout credentials. Create sandbox and production channels separately, and check availability in the target environment. Sandbox addresses are synthetic; each deposit simulation creates a new test deposit rather than updating an earlier simulation.
|
|
2653
|
+
|
|
2654
|
+
Credit channel deposits only after confirmation. Verify webhook signatures and require \`confirmed\` with \`is_final\` before crediting a deposit. Webhooks can repeat or arrive out of order: deduplicate deliveries by \`event_id\` and prevent duplicate credit for the same deposit.
|
|
2655
|
+
|
|
2656
|
+
Use the confirmed-deposit feed to reconcile deposits. Save every returned \`next_cursor\`, even on empty pages, and inspect \`blocked\` when present. \`confirmed_from\` bounds the first poll and forms part of the cursor\u2019s fingerprint; keep its value unchanged when continuing with that cursor. Feed cursors expire 24 hours after issue, so poll at least daily. If a cursor expires, restart with a bounded \`confirmed_from\` and retain deposit deduplication.
|
|
2657
|
+
|
|
2658
|
+
Start with the flow you chose. The recommendation needs no credentials; API calls need test credentials.
|
|
2659
|
+
|
|
2660
|
+
For invoices, call \`create_invoice\` with \`project_id\`, \`external_order_id\`, \`amount\` as a decimal string, and \`currency\`. Save the invoice\u2019s link to your order, and use the returned \`payment_url\` for checkout. Test a payment with \`simulate_invoice_payment\`, passing \`invoice_id\` and \`stage\`.
|
|
2661
|
+
|
|
2662
|
+
For payment channels, call \`create_payment_channel\` with \`project_id\` and your customer\u2019s \`external_id\`. Save the channel\u2019s link to that customer. Check the returned networks and addresses; an address may still be provisioning. Call \`get_payment_channel\` again to check readiness and addresses. Call \`simulate_payment_channel_deposit\` with \`payment_channel_id\`, \`amount\` as a decimal string, \`currency\`, and \`network\`; \`stage\` is optional. Read any deposit status with \`get_payment_channel_deposit\`, or use \`list_payment_channel_deposits\` for the confirmed-deposit feed.
|
|
2663
|
+
|
|
2664
|
+
If you chose both, follow both paths. Before changing an order or customer balance, verify webhook signatures, apply the flow\u2019s confirmation checks, and deduplicate events. Credit channel deposits only when \`confirmed\` and \`is_final\`.`;
|
|
2665
|
+
var RECOMMENDATIONS = {
|
|
2666
|
+
order_checkout: {
|
|
2667
|
+
recommendation: "invoice",
|
|
2668
|
+
summary: "Use an invoice for each order: it has a set amount, an expiry, payment statuses, and hosted checkout. Explain how this fits the order flow while respecting the merchant\u2019s stated preference."
|
|
2669
|
+
},
|
|
2670
|
+
repeat_deposits: {
|
|
2671
|
+
recommendation: "payment_channel",
|
|
2672
|
+
summary: "Use a payment channel for repeated deposits from one payer to reusable addresses per network. Track credited deposits separately; transfers below the minimum are not credited or returned. The channel sets no amount or expiry."
|
|
2673
|
+
},
|
|
2674
|
+
both: {
|
|
2675
|
+
recommendation: "both",
|
|
2676
|
+
summary: "Use invoices for individual orders and payment channels for repeated account top-ups. Explain which customer action uses each flow, and respect any preference the merchant has already stated."
|
|
2677
|
+
},
|
|
2678
|
+
unsure: {
|
|
2679
|
+
recommendation: "unsure",
|
|
2680
|
+
summary: "Do not choose a flow yet. Ask: \u201CWill your customer pay for each order, repeatedly top up an account, or do both?\u201D Use the answer and the merchant\u2019s preferences to guide the recommendation."
|
|
1415
2681
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
} catch {
|
|
1437
|
-
return error("configFile");
|
|
1438
|
-
}
|
|
1439
|
-
const servers2 = root2.mcp_servers;
|
|
1440
|
-
if (servers2 !== void 0 && !object(servers2)) error("configFile");
|
|
1441
|
-
const existing2 = servers2?.paymos;
|
|
1442
|
-
if (existing2 !== void 0) {
|
|
1443
|
-
if (!equalData(existing2, entry)) error("conflict");
|
|
1444
|
-
return original;
|
|
1445
|
-
}
|
|
1446
|
-
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
1447
|
-
const block = stringifyToml({ mcp_servers: { paymos: entry } }).replace(/\r?\n/g, eol);
|
|
1448
|
-
const next2 = (original ?? "") + eol + block;
|
|
1449
|
-
try {
|
|
1450
|
-
const expected2 = { ...root2, mcp_servers: { ...servers2, paymos: entry } };
|
|
1451
|
-
if (!equalData(parseToml(next2), expected2)) error("configFile");
|
|
1452
|
-
} catch {
|
|
1453
|
-
return error("configFile");
|
|
2682
|
+
};
|
|
2683
|
+
function registerIntegrationRecommendation(server) {
|
|
2684
|
+
server.registerTool(
|
|
2685
|
+
"recommend_payment_integration",
|
|
2686
|
+
{
|
|
2687
|
+
title: "Recommend a payment integration",
|
|
2688
|
+
description: "Recommend invoices, payment channels, or both from the merchant\u2019s payment flow. Explain the fit and relevant lifecycle. When information is missing, return a targeted question instead of choosing. Respect an explicit merchant choice.",
|
|
2689
|
+
inputSchema: {
|
|
2690
|
+
scenario: z2.enum(["order_checkout", "repeat_deposits", "both", "unsure"]).optional().describe("Choose order_checkout for payment per order, repeat_deposits for repeated customer account top-ups, or both when both flows are needed. Use unsure when the payment flow is unclear; ask whether the customer pays for each order, repeatedly tops up an account, or does both. Respect the merchant\u2019s explicit choice.")
|
|
2691
|
+
},
|
|
2692
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
|
|
2693
|
+
},
|
|
2694
|
+
async ({ scenario }) => {
|
|
2695
|
+
const selected = scenario ?? "unsure";
|
|
2696
|
+
return {
|
|
2697
|
+
content: [{
|
|
2698
|
+
type: "text",
|
|
2699
|
+
text: JSON.stringify({ scenario: selected, ...RECOMMENDATIONS[selected], guide: GUIDE }, null, 2)
|
|
2700
|
+
}]
|
|
2701
|
+
};
|
|
1454
2702
|
}
|
|
1455
|
-
|
|
1456
|
-
}
|
|
1457
|
-
const root = jsonConfig(text);
|
|
1458
|
-
const group = client === "opencode" ? "mcp" : client === "vscode" ? "servers" : "mcpServers";
|
|
1459
|
-
const servers = root[group];
|
|
1460
|
-
if (servers !== void 0 && !object(servers)) error("configFile");
|
|
1461
|
-
const existing = servers?.paymos;
|
|
1462
|
-
if (existing !== void 0) {
|
|
1463
|
-
if (!isDeepStrictEqual(existing, entry)) error("conflict");
|
|
1464
|
-
return text;
|
|
1465
|
-
}
|
|
1466
|
-
const next = applyEdits(text, modify(text, [group, "paymos"], entry, {
|
|
1467
|
-
formattingOptions: { insertSpaces: true, tabSize: 2, eol: text.includes("\r\n") ? "\r\n" : "\n" }
|
|
1468
|
-
}));
|
|
1469
|
-
const expected = { ...root, [group]: { ...servers, paymos: entry } };
|
|
1470
|
-
if (!isDeepStrictEqual(jsonConfig(next), expected)) error("configFile");
|
|
1471
|
-
return next;
|
|
1472
|
-
}
|
|
1473
|
-
function writeConfig(before, content) {
|
|
1474
|
-
mkdirSync(dirname(before.path), { recursive: true, mode: 448 });
|
|
1475
|
-
const temp = join(dirname(before.path), `.paymos-${randomUUID()}.tmp`);
|
|
1476
|
-
let created = false;
|
|
1477
|
-
try {
|
|
1478
|
-
writeFileSync(temp, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
1479
|
-
created = true;
|
|
1480
|
-
if (process.platform !== "win32") chmodSync(temp, 384);
|
|
1481
|
-
const identity = lstatSync2(temp);
|
|
1482
|
-
assertUnchanged(before);
|
|
1483
|
-
if (before.content === null) linkSync(temp, before.path);
|
|
1484
|
-
else renameSync(temp, before.path);
|
|
1485
|
-
return { ino: identity.ino, dev: identity.dev };
|
|
1486
|
-
} finally {
|
|
1487
|
-
if (created && existsSync(temp)) unlinkSync(temp);
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
async function ask(io, label, secret = false) {
|
|
1491
|
-
if (!io.interactive) error("nonInteractive");
|
|
1492
|
-
return (await io.ask(label, secret)).trim();
|
|
2703
|
+
);
|
|
1493
2704
|
}
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
settled = true;
|
|
1509
|
-
muted = false;
|
|
1510
|
-
process.stdout.write("\n");
|
|
1511
|
-
reader.close();
|
|
1512
|
-
reject(new Error(SETUP_COPY.errors.cancelled));
|
|
1513
|
-
};
|
|
1514
|
-
reader.once("SIGINT", cancel);
|
|
1515
|
-
reader.once("close", () => {
|
|
1516
|
-
if (!settled) cancel();
|
|
1517
|
-
});
|
|
1518
|
-
process.stdout.write(`${label}: `);
|
|
1519
|
-
muted = secret;
|
|
1520
|
-
reader.question("", (answer) => {
|
|
1521
|
-
settled = true;
|
|
1522
|
-
muted = false;
|
|
1523
|
-
if (secret) process.stdout.write("\n");
|
|
1524
|
-
reader.close();
|
|
1525
|
-
accept(answer);
|
|
1526
|
-
});
|
|
1527
|
-
})
|
|
1528
|
-
};
|
|
2705
|
+
|
|
2706
|
+
// src/version.ts
|
|
2707
|
+
var MCP_VERSION = "1.6.0";
|
|
2708
|
+
|
|
2709
|
+
// src/server.ts
|
|
2710
|
+
function buildServer(gateway) {
|
|
2711
|
+
const server = new McpServer(
|
|
2712
|
+
{ name: "paymos", version: MCP_VERSION },
|
|
2713
|
+
{ instructions: INTEGRATION_INSTRUCTIONS }
|
|
2714
|
+
);
|
|
2715
|
+
registerTools(server, gateway);
|
|
2716
|
+
registerIntegrationRecommendation(server);
|
|
2717
|
+
registerResources(server);
|
|
2718
|
+
return server;
|
|
1529
2719
|
}
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
2720
|
+
|
|
2721
|
+
// src/index.ts
|
|
2722
|
+
async function main(env = process.env, argv = process.argv.slice(2)) {
|
|
2723
|
+
if (argv[0] === "setup") {
|
|
2724
|
+
await runSetup(argv.slice(1), env);
|
|
1534
2725
|
return;
|
|
1535
2726
|
}
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
const client = requested;
|
|
1540
|
-
const configPath = absolute(flags.config ?? defaultConfigPath(client, env, context), context);
|
|
1541
|
-
const credentialsPath = absolute(flags.credentialsFile ?? env.PAYMOS_CREDENTIALS_FILE ?? join(env.XDG_CONFIG_HOME || join(context.home, ".config"), "paymos", "mcp", "credentials.json"), context);
|
|
1542
|
-
const samePath = context.platform === "win32" ? configPath.toLowerCase() === credentialsPath.toLowerCase() : configPath === credentialsPath;
|
|
1543
|
-
if (samePath || !isAbsolute(configPath) || !isAbsolute(credentialsPath)) error("conflict");
|
|
1544
|
-
const before = snapshot(configPath);
|
|
1545
|
-
const beforeKeys = snapshot(credentialsPath);
|
|
1546
|
-
const stored = beforeKeys.content === null ? void 0 : readCredentialFile(credentialsPath);
|
|
1547
|
-
const apiKeyId = (env.PAYMOS_API_KEY_ID ?? stored?.apiKeyId ?? await ask(io, SETUP_COPY.apiKey)).trim();
|
|
1548
|
-
const apiSecret = (env.PAYMOS_API_SECRET ?? stored?.apiSecret ?? await ask(io, SETUP_COPY.apiSecret, true)).trim();
|
|
1549
|
-
const webhookSecret = (env.PAYMOS_WEBHOOK_SECRET ?? stored?.webhookSecret ?? (io.interactive ? await ask(io, SETUP_COPY.webhookSecret, true) : "")).trim();
|
|
1550
|
-
const credentials = {
|
|
1551
|
-
apiKeyId,
|
|
1552
|
-
apiSecret,
|
|
1553
|
-
...webhookSecret === "" ? {} : { webhookSecret }
|
|
1554
|
-
};
|
|
1555
|
-
if (!checkCredentials(credentials).ok) error("credentials");
|
|
1556
|
-
if (stored !== void 0 && !isDeepStrictEqual(stored, credentials)) error("conflict");
|
|
1557
|
-
const next = planClientConfig(client, before.content, credentialsPath, context.platform);
|
|
1558
|
-
if (flags.dryRun) {
|
|
1559
|
-
io.log(SETUP_COPY.preview(configPath));
|
|
1560
|
-
io.log(SETUP_COPY.preview(credentialsPath));
|
|
2727
|
+
if (argv[0] === "auth") {
|
|
2728
|
+
const code = await runAuth(argv.slice(1), env);
|
|
2729
|
+
if (code !== 0) process.exitCode = code;
|
|
1561
2730
|
return;
|
|
1562
2731
|
}
|
|
1563
|
-
if (
|
|
1564
|
-
|
|
2732
|
+
if (argv[0] === "install-secret") {
|
|
2733
|
+
await runInstallSecret(argv.slice(1));
|
|
1565
2734
|
return;
|
|
1566
2735
|
}
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
assertUnchanged(beforeKeys);
|
|
1571
|
-
if (stored === void 0) {
|
|
1572
|
-
createdKeys = writeConfig(beforeKeys, JSON.stringify(credentials, null, 2) + "\n");
|
|
1573
|
-
}
|
|
1574
|
-
if (before.content !== next) writeConfig(before, next);
|
|
1575
|
-
} catch (cause) {
|
|
1576
|
-
if (createdKeys !== void 0) {
|
|
1577
|
-
try {
|
|
1578
|
-
const stat = lstatSync2(credentialsPath);
|
|
1579
|
-
if (!stat.isSymbolicLink() && stat.ino === createdKeys.ino && stat.dev === createdKeys.dev && isDeepStrictEqual(readCredentialFile(credentialsPath), credentials)) unlinkSync(credentialsPath);
|
|
1580
|
-
} catch {
|
|
1581
|
-
}
|
|
1582
|
-
}
|
|
1583
|
-
if (cause instanceof Error && Object.values(SETUP_COPY.errors).includes(cause.message)) throw cause;
|
|
1584
|
-
error("write");
|
|
2736
|
+
if (argv[0] === "upload-file") {
|
|
2737
|
+
await runUploadFile(argv.slice(1));
|
|
2738
|
+
return;
|
|
1585
2739
|
}
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
// src/index.ts
|
|
1591
|
-
async function main(env = process.env, argv = process.argv.slice(2)) {
|
|
1592
|
-
if (argv[0] === "setup") {
|
|
1593
|
-
await runSetup(argv.slice(1), env);
|
|
2740
|
+
if (argv[0] === "download-file") {
|
|
2741
|
+
await runDownloadFile(argv.slice(1));
|
|
1594
2742
|
return;
|
|
1595
2743
|
}
|
|
1596
2744
|
if (argv[0] === "--help" || argv[0] === "-h") {
|
|
@@ -1603,7 +2751,7 @@ async function main(env = process.env, argv = process.argv.slice(2)) {
|
|
|
1603
2751
|
const server = buildServer(gateway);
|
|
1604
2752
|
await server.connect(new StdioServerTransport());
|
|
1605
2753
|
}
|
|
1606
|
-
var isDirectRun = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(
|
|
2754
|
+
var isDirectRun = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(realpathSync3(process.argv[1])).href;
|
|
1607
2755
|
if (isDirectRun) {
|
|
1608
2756
|
main().catch((error2) => {
|
|
1609
2757
|
console.error(`[paymos-mcp] fatal: ${error2 instanceof Error ? error2.message : String(error2)}`);
|