apinoa-mcp 0.2.7 → 0.2.8
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/README.md +12 -0
- package/dist/cli.js +23 -4
- package/dist/login.d.ts +36 -0
- package/dist/login.js +395 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,6 +16,17 @@ product photo into Korean"*.
|
|
|
16
16
|
Create a key under **Dashboard > API keys** at [apinoa.com](https://apinoa.com). Calls are billed to it
|
|
17
17
|
at the API's normal rates; a call that fails is not billed.
|
|
18
18
|
|
|
19
|
+
**Get a key from the terminal**
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npx apinoa-mcp login
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
It prints a code and opens an apinoa page in your browser, where you sign in and enter the code. The new key is
|
|
26
|
+
saved to `.env` in the current folder as `APINOA_API_KEY` (`--out <path>` writes it to another file,
|
|
27
|
+
`--no-browser` only prints the address). It expires after 90 days and is listed under **Dashboard > API keys**,
|
|
28
|
+
where you can revoke it. Give it to your client as below.
|
|
29
|
+
|
|
19
30
|
**Claude Code**
|
|
20
31
|
|
|
21
32
|
```sh
|
|
@@ -109,6 +120,7 @@ characters keeps as many whole items as fit, with a note saying how many were le
|
|
|
109
120
|
|---|---|---|
|
|
110
121
|
| `APINOA_API_KEY` | — | Required for every data call. |
|
|
111
122
|
| `APINOA_BASE_URL` | `https://gateway.apinoa.com` | |
|
|
123
|
+
| `APINOA_API_URL` | `https://api.apinoa.com` | Where `login` signs in. https only (http for localhost). |
|
|
112
124
|
| `APINOA_MCP_MODE` | `code` | `tools` for the 0.1 tool set. |
|
|
113
125
|
| `APINOA_MCP_DATA_DIR` | `~/.apinoa-mcp` | Where the cache, `store` and saved files live. |
|
|
114
126
|
| `APINOA_MCP_MAX_BUDGET` | `20000` | The most units one run may be given. |
|
package/dist/cli.js
CHANGED
|
@@ -3,11 +3,30 @@
|
|
|
3
3
|
* apinoa-mcp over stdio, for Claude Desktop, Claude Code, Cursor and any MCP client:
|
|
4
4
|
*
|
|
5
5
|
* APINOA_API_KEY=... npx -y apinoa-mcp
|
|
6
|
+
*
|
|
7
|
+
* and `npx apinoa-mcp login`, which gets a key in the browser and writes it to .env (see login.ts).
|
|
6
8
|
*/
|
|
7
9
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
8
10
|
import { createApinoaServer } from "./server.js";
|
|
9
|
-
|
|
10
|
-
await
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
if (process.argv[2] === "login") {
|
|
12
|
+
const { login, openInBrowser } = await import("./login.js");
|
|
13
|
+
process.exitCode = await login({
|
|
14
|
+
argv: process.argv.slice(3),
|
|
15
|
+
env: process.env,
|
|
16
|
+
cwd: process.cwd(),
|
|
17
|
+
fetch: globalThis.fetch,
|
|
18
|
+
sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
|
|
19
|
+
now: Date.now,
|
|
20
|
+
stdout: process.stdout,
|
|
21
|
+
stderr: process.stderr,
|
|
22
|
+
isTTY: process.stdout.isTTY === true,
|
|
23
|
+
openBrowser: openInBrowser,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
const server = await createApinoaServer();
|
|
28
|
+
await server.connect(new StdioServerTransport());
|
|
29
|
+
if (!process.env.APINOA_API_KEY) {
|
|
30
|
+
console.error("apinoa-mcp: APINOA_API_KEY is not set — list_platforms works, every data call will answer 401.");
|
|
31
|
+
}
|
|
13
32
|
}
|
package/dist/login.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface LoginIO {
|
|
2
|
+
/** The arguments after `login`. */
|
|
3
|
+
argv: string[];
|
|
4
|
+
env: Record<string, string | undefined>;
|
|
5
|
+
cwd: string;
|
|
6
|
+
fetch: typeof fetch;
|
|
7
|
+
sleep: (ms: number) => Promise<void>;
|
|
8
|
+
/** Milliseconds, like Date.now. */
|
|
9
|
+
now: () => number;
|
|
10
|
+
stdout: {
|
|
11
|
+
write(text: string): unknown;
|
|
12
|
+
};
|
|
13
|
+
stderr: {
|
|
14
|
+
write(text: string): unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Whether stdout is a terminal. The browser is opened only when it is. */
|
|
17
|
+
isTTY: boolean;
|
|
18
|
+
openBrowser: (url: string) => void;
|
|
19
|
+
}
|
|
20
|
+
/** Runs `login` and returns the process exit code: 0 once a key is saved, 1 otherwise. */
|
|
21
|
+
export declare function login(io: LoginIO): Promise<number>;
|
|
22
|
+
/** `apinoa_mcp_…3f9a`: enough to tell keys apart in the dashboard, never enough to use one. */
|
|
23
|
+
export declare function maskKey(key: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* The .env text with every APINOA_API_KEY line (also `export APINOA_API_KEY=`) set to the key, and every other
|
|
26
|
+
* line and line ending untouched; with none, one line is appended in the file's own line-ending style. The
|
|
27
|
+
* text is read and written as latin1, so bytes that are not UTF-8 survive.
|
|
28
|
+
*/
|
|
29
|
+
export declare function setEnvKey(text: string, key: string): {
|
|
30
|
+
text: string;
|
|
31
|
+
replaced: number;
|
|
32
|
+
};
|
|
33
|
+
/** The display prefixes of the keys the server says this sign-in revoked (apinoa_revoked_keys), safe to print. */
|
|
34
|
+
export declare function revokedKeys(value: unknown): string[];
|
|
35
|
+
/** Opens a URL in the default browser without a shell; failures are ignored (the address is printed anyway). */
|
|
36
|
+
export declare function openInBrowser(url: string): void;
|
package/dist/login.js
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `apinoa-mcp login`: gets an API key through the OAuth 2.0 device authorization grant (RFC 8628) and writes
|
|
3
|
+
* it to a .env file as APINOA_API_KEY.
|
|
4
|
+
*
|
|
5
|
+
* The person opens apinoa's page, signs in and types the code shown here; this side polls the token endpoint
|
|
6
|
+
* until they approve, cancel, or the code expires. The key is never printed: only its prefix and last four
|
|
7
|
+
* characters.
|
|
8
|
+
*
|
|
9
|
+
* Everything the command touches comes in through `LoginIO`, so it runs in tests without a terminal, a
|
|
10
|
+
* network or a browser; cli.ts passes the real ones.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from "node:child_process";
|
|
13
|
+
import { constants } from "node:fs";
|
|
14
|
+
import { access, chmod, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
15
|
+
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
16
|
+
const DEFAULT_API = "https://api.apinoa.com";
|
|
17
|
+
const CLIENT_ID = "apinoa-cli";
|
|
18
|
+
const GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
19
|
+
const KEY_NAME = "APINOA_API_KEY";
|
|
20
|
+
const KEY_PREFIX = "apinoa_mcp_";
|
|
21
|
+
const MAX_BACKOFF_MS = 60_000;
|
|
22
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
23
|
+
const AGAIN = "Run `npx apinoa-mcp login` again.";
|
|
24
|
+
const DASHBOARD = "Dashboard → API keys at apinoa.com";
|
|
25
|
+
// RFC 6750 b64token: what a bearer token may contain. Anything else (a newline above all) could add lines to .env.
|
|
26
|
+
const TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/;
|
|
27
|
+
const USAGE = `Usage: npx apinoa-mcp login [--out <path>] [--no-browser]
|
|
28
|
+
|
|
29
|
+
Signs in to apinoa in your browser and saves a new API key to .env as ${KEY_NAME}.
|
|
30
|
+
|
|
31
|
+
--out <path> Write the key to this file instead of .env in the current folder
|
|
32
|
+
--no-browser Print the address without opening it
|
|
33
|
+
-h, --help Show this help
|
|
34
|
+
`;
|
|
35
|
+
/** Runs `login` and returns the process exit code: 0 once a key is saved, 1 otherwise. */
|
|
36
|
+
export async function login(io) {
|
|
37
|
+
const out = (line = "") => void io.stdout.write(line + "\n");
|
|
38
|
+
const fail = (line) => {
|
|
39
|
+
io.stderr.write(line + "\n");
|
|
40
|
+
return 1;
|
|
41
|
+
};
|
|
42
|
+
const args = parseArgs(io.argv);
|
|
43
|
+
if ("error" in args) {
|
|
44
|
+
io.stderr.write(`${args.error}\n\n${USAGE}`);
|
|
45
|
+
return 1;
|
|
46
|
+
}
|
|
47
|
+
if (args.help) {
|
|
48
|
+
io.stdout.write(USAGE);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
const base = apiBase(io.env.APINOA_API_URL);
|
|
52
|
+
if (!base)
|
|
53
|
+
return fail(`APINOA_API_URL must be an https:// address (http:// only for localhost): ${clean(io.env.APINOA_API_URL ?? "")}`);
|
|
54
|
+
const file = resolve(io.cwd, args.envFile ?? ".env");
|
|
55
|
+
const shown = display(io.cwd, file);
|
|
56
|
+
// Before a key exists, so a file that cannot be written does not leave one behind.
|
|
57
|
+
const unwritable = await cannotWrite(file, shown);
|
|
58
|
+
if (unwritable)
|
|
59
|
+
return fail(unwritable);
|
|
60
|
+
// Step 1: a device code and the code the person types.
|
|
61
|
+
let start;
|
|
62
|
+
try {
|
|
63
|
+
start = await post(io, `${base}/oauth/device_authorization`, { client_id: CLIENT_ID, scope: "apinoa" });
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
return fail(`Could not reach ${base} (${reason(err)}).`);
|
|
67
|
+
}
|
|
68
|
+
if (start.status !== 200) {
|
|
69
|
+
const busy = start.status === 429 || start.status >= 500;
|
|
70
|
+
return fail(`apinoa could not start a sign-in (${describe(start)}).${busy ? " Try again in a minute." : ""}`);
|
|
71
|
+
}
|
|
72
|
+
const grant = start.body ?? {};
|
|
73
|
+
const deviceCode = typeof grant.device_code === "string" ? grant.device_code : "";
|
|
74
|
+
const userCode = typeof grant.user_code === "string" ? clean(grant.user_code).slice(0, 64) : "";
|
|
75
|
+
const page = typeof grant.verification_uri === "string" ? parseUrl(grant.verification_uri) : undefined;
|
|
76
|
+
if (!deviceCode || !userCode || !page || !/^https?:$/.test(page.protocol)) {
|
|
77
|
+
return fail("apinoa answered the sign-in request with something this version does not understand. Update apinoa-mcp and try again.");
|
|
78
|
+
}
|
|
79
|
+
const expiresIn = positive(grant.expires_in) ?? 600;
|
|
80
|
+
let interval = (positive(grant.interval) ?? 5) * 1000;
|
|
81
|
+
const deadline = io.now() + expiresIn * 1000;
|
|
82
|
+
const ours = page.origin === new URL(base).origin;
|
|
83
|
+
out("To create an API key, open this page:");
|
|
84
|
+
out();
|
|
85
|
+
out(` ${clean(page.href)}`);
|
|
86
|
+
out();
|
|
87
|
+
out("and enter the code:");
|
|
88
|
+
out();
|
|
89
|
+
out(` ${userCode}`);
|
|
90
|
+
out();
|
|
91
|
+
out("Enter it only on that apinoa page, and only because you started this yourself. Anyone else who asks you to enter a code is trying to get into your account.");
|
|
92
|
+
out();
|
|
93
|
+
if (!ours) {
|
|
94
|
+
io.stderr.write(`Warning: that address is not on ${new URL(base).origin}. Check it before you visit it.\n`);
|
|
95
|
+
}
|
|
96
|
+
else if (io.isTTY && !io.env.CI && !args.noBrowser) {
|
|
97
|
+
io.openBrowser(page.href);
|
|
98
|
+
out("Opening it in your browser…");
|
|
99
|
+
}
|
|
100
|
+
out("Waiting for approval…");
|
|
101
|
+
// Step 2: poll until the person approves or cancels, or the code expires.
|
|
102
|
+
let wait = interval;
|
|
103
|
+
let lastProblem = "";
|
|
104
|
+
for (;;) {
|
|
105
|
+
const left = deadline - io.now();
|
|
106
|
+
if (left <= wait) {
|
|
107
|
+
if (left > 0)
|
|
108
|
+
await io.sleep(left);
|
|
109
|
+
return fail(`The code expired.${lastProblem ? ` The last attempt to reach apinoa failed (${lastProblem}).` : ""} ${AGAIN}`);
|
|
110
|
+
}
|
|
111
|
+
await io.sleep(wait);
|
|
112
|
+
let answer;
|
|
113
|
+
try {
|
|
114
|
+
answer = await post(io, `${base}/oauth/token`, { grant_type: GRANT_TYPE, device_code: deviceCode, client_id: CLIENT_ID });
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
lastProblem = reason(err);
|
|
118
|
+
wait = Math.min(Math.max(wait, 1000) * 2, MAX_BACKOFF_MS);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (answer.status === 429 || answer.status >= 500) {
|
|
122
|
+
lastProblem = `HTTP ${answer.status}`;
|
|
123
|
+
wait = Math.min(Math.max(wait, 1000) * 2, MAX_BACKOFF_MS);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
lastProblem = "";
|
|
127
|
+
if (answer.status !== 200) {
|
|
128
|
+
const error = answer.body?.error;
|
|
129
|
+
if (error === "authorization_pending") {
|
|
130
|
+
wait = interval;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (error === "slow_down") {
|
|
134
|
+
interval += 5000;
|
|
135
|
+
wait = interval;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (error === "access_denied")
|
|
139
|
+
return fail("The sign-in was cancelled, so no key was created.");
|
|
140
|
+
if (error === "expired_token")
|
|
141
|
+
return fail(`The code expired. ${AGAIN}`);
|
|
142
|
+
return fail(`apinoa refused the sign-in (${describe(answer)}). ${AGAIN}`);
|
|
143
|
+
}
|
|
144
|
+
const token = answer.body ?? {};
|
|
145
|
+
const key = token.access_token;
|
|
146
|
+
if (typeof key !== "string" || !TOKEN.test(key)) {
|
|
147
|
+
return fail("apinoa approved the sign-in but answered with a key this version cannot save. Update apinoa-mcp and try again.");
|
|
148
|
+
}
|
|
149
|
+
return saved(io, file, shown, key, token);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** Writes the key, says where it went, and warns when the file is not ignored by git. */
|
|
153
|
+
async function saved(io, file, shown, key, body) {
|
|
154
|
+
const masked = maskKey(key);
|
|
155
|
+
let how;
|
|
156
|
+
try {
|
|
157
|
+
how = await saveKey(file, key);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
io.stderr.write(`Could not save the key to ${shown} (${reason(err)}). Revoke it (${masked}) in ${DASHBOARD}, then run \`npx apinoa-mcp login\` again.\n`);
|
|
161
|
+
return 1;
|
|
162
|
+
}
|
|
163
|
+
const lines = [`Approved. The key (${masked}) is saved in ${shown} as ${KEY_NAME}${how === "replaced" ? ", replacing the one that was there" : ""}.`];
|
|
164
|
+
const seconds = positive(body.expires_in);
|
|
165
|
+
const days = seconds === undefined ? undefined : seconds >= 86_400 ? Math.round(seconds / 86_400) : 0;
|
|
166
|
+
const expiry = days === undefined ? "" : days === 0 ? "It expires in less than a day. " : `It expires in ${days} day${days === 1 ? "" : "s"}. `;
|
|
167
|
+
lines.push(`${expiry}It is listed in ${DASHBOARD}, where you can revoke it.`);
|
|
168
|
+
const credit = creditUsd(body.apinoa_credit_usd);
|
|
169
|
+
if (credit)
|
|
170
|
+
lines.push(`Your account received $${credit} of evaluation credit.`);
|
|
171
|
+
const revoked = revokedKeys(body.apinoa_revoked_keys);
|
|
172
|
+
if (revoked.length) {
|
|
173
|
+
lines.push(`apinoa keeps a few CLI keys per account, so this sign-in revoked the oldest (${revoked.map((p) => `${p}…`).join(", ")}). A project still using ${revoked.length === 1 ? "it" : "them"} needs \`npx apinoa-mcp login\` again.`);
|
|
174
|
+
}
|
|
175
|
+
io.stdout.write(lines.join("\n") + "\n");
|
|
176
|
+
if ((await gitIgnored(file)) === false) {
|
|
177
|
+
io.stderr.write(`Warning: ${shown} is not ignored by git. Add it to .gitignore so the key is never committed.\n`);
|
|
178
|
+
}
|
|
179
|
+
if (process.platform !== "win32") {
|
|
180
|
+
const mode = await stat(file).then((s) => s.mode & 0o777, () => undefined);
|
|
181
|
+
if (mode !== undefined && mode & 0o077) {
|
|
182
|
+
io.stderr.write(`Warning: other users on this computer can read ${shown} (mode ${mode.toString(8)}). Run \`chmod 600 ${shown}\`.\n`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return 0;
|
|
186
|
+
}
|
|
187
|
+
function parseArgs(argv) {
|
|
188
|
+
const args = { envFile: undefined, noBrowser: false, help: false };
|
|
189
|
+
for (let i = 0; i < argv.length; i++) {
|
|
190
|
+
const a = argv[i];
|
|
191
|
+
if (a === "-h" || a === "--help")
|
|
192
|
+
args.help = true;
|
|
193
|
+
else if (a === "--no-browser")
|
|
194
|
+
args.noBrowser = true;
|
|
195
|
+
// Not --env-file: Node reads that flag anywhere on the command line, past the script name, and
|
|
196
|
+
// exits before this runs when the file does not exist yet (or loads it into this process when it does).
|
|
197
|
+
else if (a === "--out" || a.startsWith("--out=")) {
|
|
198
|
+
const value = a === "--out" ? argv[++i] : a.slice("--out=".length);
|
|
199
|
+
if (!value)
|
|
200
|
+
return { error: "--out needs a path." };
|
|
201
|
+
args.envFile = value;
|
|
202
|
+
}
|
|
203
|
+
else
|
|
204
|
+
return { error: `Unknown option: ${clean(a)}` };
|
|
205
|
+
}
|
|
206
|
+
return args;
|
|
207
|
+
}
|
|
208
|
+
/** The API's base URL, or undefined when it is not https (http is allowed for this machine only). */
|
|
209
|
+
function apiBase(value) {
|
|
210
|
+
const raw = value?.trim() || DEFAULT_API;
|
|
211
|
+
const url = parseUrl(raw);
|
|
212
|
+
if (!url)
|
|
213
|
+
return undefined;
|
|
214
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
215
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local))
|
|
216
|
+
return undefined;
|
|
217
|
+
return raw.replace(/\/+$/, "");
|
|
218
|
+
}
|
|
219
|
+
async function post(io, url, form) {
|
|
220
|
+
const res = await io.fetch(url, {
|
|
221
|
+
method: "POST",
|
|
222
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", "user-agent": "apinoa-mcp" },
|
|
223
|
+
body: new URLSearchParams(form).toString(),
|
|
224
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
225
|
+
});
|
|
226
|
+
const text = await res.text();
|
|
227
|
+
let body;
|
|
228
|
+
try {
|
|
229
|
+
body = JSON.parse(text);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
body = undefined;
|
|
233
|
+
}
|
|
234
|
+
return { status: res.status, body: body && typeof body === "object" && !Array.isArray(body) ? body : undefined };
|
|
235
|
+
}
|
|
236
|
+
/** An RFC 6749 error answer as `code: description`, or the HTTP status when it is not one. */
|
|
237
|
+
function describe(a) {
|
|
238
|
+
const code = typeof a.body?.error === "string" ? clean(a.body.error).slice(0, 80) : `HTTP ${a.status}`;
|
|
239
|
+
const text = typeof a.body?.error_description === "string" ? clean(a.body.error_description).slice(0, 300) : "";
|
|
240
|
+
return text ? `${code}: ${text}` : code;
|
|
241
|
+
}
|
|
242
|
+
/** `apinoa_mcp_…3f9a`: enough to tell keys apart in the dashboard, never enough to use one. */
|
|
243
|
+
export function maskKey(key) {
|
|
244
|
+
const tail = key.length >= 12 ? key.slice(-4) : "";
|
|
245
|
+
return `${key.startsWith(KEY_PREFIX) ? KEY_PREFIX : ""}…${tail}`;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The .env text with every APINOA_API_KEY line (also `export APINOA_API_KEY=`) set to the key, and every other
|
|
249
|
+
* line and line ending untouched; with none, one line is appended in the file's own line-ending style. The
|
|
250
|
+
* text is read and written as latin1, so bytes that are not UTF-8 survive.
|
|
251
|
+
*/
|
|
252
|
+
export function setEnvKey(text, key) {
|
|
253
|
+
const eol = text.match(/\r?\n/)?.[0] ?? "\n";
|
|
254
|
+
const line = new RegExp(`^((?:\\xEF\\xBB\\xBF)?[ \\t]*)(export[ \\t]+)?${KEY_NAME}[ \\t]*=`);
|
|
255
|
+
let replaced = 0;
|
|
256
|
+
const chunks = text.split(/(?<=\n)/).map((chunk) => {
|
|
257
|
+
const end = chunk.endsWith("\r\n") ? "\r\n" : chunk.endsWith("\n") ? "\n" : "";
|
|
258
|
+
const m = line.exec(chunk.slice(0, chunk.length - end.length));
|
|
259
|
+
if (!m)
|
|
260
|
+
return chunk;
|
|
261
|
+
replaced++;
|
|
262
|
+
return `${m[1]}${m[2] ? "export " : ""}${KEY_NAME}=${key}${end}`;
|
|
263
|
+
});
|
|
264
|
+
if (replaced)
|
|
265
|
+
return { text: chunks.join(""), replaced };
|
|
266
|
+
const sep = text === "" || text.endsWith("\n") ? "" : eol;
|
|
267
|
+
return { text: `${text}${sep}${KEY_NAME}=${key}${eol}`, replaced };
|
|
268
|
+
}
|
|
269
|
+
async function saveKey(file, key) {
|
|
270
|
+
let before;
|
|
271
|
+
try {
|
|
272
|
+
before = await readFile(file, "latin1");
|
|
273
|
+
}
|
|
274
|
+
catch (err) {
|
|
275
|
+
if (err.code !== "ENOENT")
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
if (before === undefined) {
|
|
279
|
+
await writeFile(file, `${KEY_NAME}=${key}\n`, { encoding: "latin1", mode: 0o600, flag: "wx" });
|
|
280
|
+
await chmod(file, 0o600).catch(() => { });
|
|
281
|
+
return "created";
|
|
282
|
+
}
|
|
283
|
+
const next = setEnvKey(before, key);
|
|
284
|
+
await writeFile(file, next.text, "latin1");
|
|
285
|
+
return next.replaced ? "replaced" : "added";
|
|
286
|
+
}
|
|
287
|
+
/** Why the key could not be written to `file`, checked before one is created; undefined when it can. */
|
|
288
|
+
async function cannotWrite(file, shown) {
|
|
289
|
+
try {
|
|
290
|
+
if (!(await stat(file)).isFile())
|
|
291
|
+
return `${shown} is not a file.`;
|
|
292
|
+
await access(file, constants.R_OK | constants.W_OK);
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
catch (err) {
|
|
296
|
+
const code = err.code;
|
|
297
|
+
if (code !== "ENOENT")
|
|
298
|
+
return `Cannot write ${shown} (${code ?? reason(err)}).`;
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
if (!(await stat(dirname(file))).isDirectory())
|
|
302
|
+
throw new Error("not a folder");
|
|
303
|
+
await access(dirname(file), constants.W_OK);
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
return `Cannot create ${shown}: its folder does not exist or cannot be written to.`;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** The display prefixes of the keys the server says this sign-in revoked (apinoa_revoked_keys), safe to print. */
|
|
311
|
+
export function revokedKeys(value) {
|
|
312
|
+
if (!Array.isArray(value))
|
|
313
|
+
return [];
|
|
314
|
+
return value.filter((v) => typeof v === "string" && /^[A-Za-z0-9_]{1,64}$/.test(v)).slice(0, 10);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* true when git ignores the file, false when it does not, undefined when git cannot tell (no git, no
|
|
318
|
+
* repository). A symlinked .env is checked at both ends: git ignoring the link says nothing about the file
|
|
319
|
+
* it points to, which may sit in a repository of its own.
|
|
320
|
+
*/
|
|
321
|
+
async function gitIgnored(file) {
|
|
322
|
+
const here = await checkIgnore(file);
|
|
323
|
+
const real = await realpath(file).catch(() => file);
|
|
324
|
+
if (real === file)
|
|
325
|
+
return here;
|
|
326
|
+
const there = await checkIgnore(real);
|
|
327
|
+
if (here === false || there === false)
|
|
328
|
+
return false;
|
|
329
|
+
return here ?? there;
|
|
330
|
+
}
|
|
331
|
+
function checkIgnore(file) {
|
|
332
|
+
return new Promise((done) => {
|
|
333
|
+
try {
|
|
334
|
+
const child = spawn("git", ["check-ignore", "-q", "--", basename(file)], { cwd: dirname(file), stdio: "ignore", timeout: 10_000 });
|
|
335
|
+
child.on("error", () => done(undefined));
|
|
336
|
+
child.on("close", (code) => done(code === 0 ? true : code === 1 ? false : undefined));
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
done(undefined);
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
/** Opens a URL in the default browser without a shell; failures are ignored (the address is printed anyway). */
|
|
344
|
+
export function openInBrowser(url) {
|
|
345
|
+
let cmd;
|
|
346
|
+
let args;
|
|
347
|
+
if (process.platform === "darwin")
|
|
348
|
+
[cmd, args] = ["open", [url]];
|
|
349
|
+
else if (process.platform === "win32") {
|
|
350
|
+
// cmd reads its own command line, so a character it treats specially is not passed to it at all.
|
|
351
|
+
if (/[&|<>^%!"\s]/.test(url))
|
|
352
|
+
return;
|
|
353
|
+
[cmd, args] = ["cmd", ["/c", "start", "", url]];
|
|
354
|
+
}
|
|
355
|
+
else
|
|
356
|
+
[cmd, args] = ["xdg-open", [url]];
|
|
357
|
+
try {
|
|
358
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
359
|
+
child.on("error", () => { });
|
|
360
|
+
child.unref();
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
// The address is on screen; opening it is a convenience.
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function creditUsd(value) {
|
|
367
|
+
const text = typeof value === "number" && Number.isFinite(value) ? value.toFixed(2) : typeof value === "string" ? value.trim() : "";
|
|
368
|
+
return /^\d{1,9}(\.\d{1,6})?$/.test(text) && Number(text) > 0 ? text : undefined;
|
|
369
|
+
}
|
|
370
|
+
function positive(value) {
|
|
371
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
372
|
+
}
|
|
373
|
+
function parseUrl(value) {
|
|
374
|
+
try {
|
|
375
|
+
return new URL(value);
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** A path as typed relative to the folder the command ran in, or absolute when it is outside it. */
|
|
382
|
+
function display(cwd, file) {
|
|
383
|
+
const rel = relative(cwd, file);
|
|
384
|
+
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : file;
|
|
385
|
+
}
|
|
386
|
+
function reason(err) {
|
|
387
|
+
const e = err;
|
|
388
|
+
if (e?.name === "TimeoutError")
|
|
389
|
+
return "timed out";
|
|
390
|
+
return clean(e?.cause?.code ?? e?.code ?? e?.cause?.message ?? e?.message ?? String(err)).slice(0, 200);
|
|
391
|
+
}
|
|
392
|
+
/** Text from elsewhere, without control characters, so it cannot move the cursor or recolour the terminal. */
|
|
393
|
+
function clean(text) {
|
|
394
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
|
395
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apinoa-mcp",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"mcpName": "io.github.apinoahq/apinoa-mcp",
|
|
5
5
|
"description": "MCP server for apinoa: marketplace products, social posts, search results and AI answers (Amazon, TikTok, Google, ChatGPT and more) for Claude Code, Codex, Cursor and any MCP client. Code mode: the model writes TypeScript against a typed client, run in a sandbox.",
|
|
6
6
|
"license": "MIT",
|