@zenlayer/lune-mcp 0.0.0-stage → 1.1.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.
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/shared/brand.ts
4
+ var BRAND_NAME = "Lune.io";
5
+ var BRAND_SLUG = BRAND_NAME.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
6
+ var SERVER_NAME = "lune-io";
7
+ var MERCHANT_ENTITY = "Zenlayer Inc.";
8
+ var SERVER_TITLE = BRAND_NAME;
9
+ var SERVER_WEBSITE_URL = "https://www.lune.io";
10
+ var SERVER_ICONS = [
11
+ { src: `${SERVER_WEBSITE_URL}/icon.svg`, mimeType: "image/svg+xml", sizes: ["any"] }
12
+ ];
13
+
14
+ // package.json
15
+ var package_default = {
16
+ name: "@zenlayer/lune-mcp",
17
+ version: "1.1.0",
18
+ description: "MCP server and CLI for the Lune.io platform \u2014 Lune.io Console and supplier portal tools over MCP",
19
+ homepage: "https://www.lune.io",
20
+ type: "module",
21
+ license: "UNLICENSED",
22
+ engines: {
23
+ node: ">=20"
24
+ },
25
+ bin: {
26
+ "lune-mcp": "dist/cli.js"
27
+ },
28
+ files: [
29
+ "dist"
30
+ ],
31
+ exports: {
32
+ ".": "./dist/index.js"
33
+ },
34
+ scripts: {
35
+ prepare: "node scripts/install-hooks.mjs",
36
+ predev: "node scripts/install-hooks.mjs",
37
+ pretest: "node scripts/install-hooks.mjs",
38
+ build: "rm -rf dist && tsup",
39
+ dev: "tsup --watch",
40
+ typecheck: "tsc --noEmit",
41
+ lint: "biome check . && npm run check:zod && npm run check:brand && npm run check:docs",
42
+ "lint:fix": "biome check --write .",
43
+ "check:zod": "node scripts/check-zod-imports.mjs",
44
+ "check:brand": "node scripts/check-brand.mjs",
45
+ "check:docs": "node scripts/vendor/delivery/docs-gate.mjs --ci",
46
+ "check:docs:sync": "node scripts/vendor/delivery/docs-gate.mjs sync",
47
+ "check:test-cases": "node scripts/check-test-cases.mjs",
48
+ test: "vitest run",
49
+ "test:watch": "vitest",
50
+ "release:guard": "node scripts/prod-flow.mjs guard",
51
+ "prod:sync": "node scripts/prod-flow.mjs sync",
52
+ "prod:ship": "node scripts/prod-flow.mjs ship",
53
+ release: "node scripts/release.mjs stable",
54
+ "release:rc": "node scripts/release.mjs rc",
55
+ prepublishOnly: "npm run build"
56
+ },
57
+ dependencies: {
58
+ "@hono/node-server": "^1.19.17",
59
+ "@modelcontextprotocol/node": "^2.0.0",
60
+ "@modelcontextprotocol/server": "^2.0.0",
61
+ commander: "^14.0.0",
62
+ hono: "^4.11.0",
63
+ ioredis: "^5.11.1",
64
+ open: "^11.0.0",
65
+ zod: "^4.2.0"
66
+ },
67
+ optionalDependencies: {
68
+ "@napi-rs/keyring": "^1.3.0"
69
+ },
70
+ devDependencies: {
71
+ "@biomejs/biome": "^2.0.0",
72
+ "@modelcontextprotocol/client": "^2.0.0",
73
+ "@types/node": "^22.0.0",
74
+ tsup: "^8.0.0",
75
+ typescript: "^5.0.0",
76
+ vitest: "^3.0.0"
77
+ },
78
+ publishConfig: {
79
+ registry: "https://registry.npmjs.org/",
80
+ access: "public"
81
+ }
82
+ };
83
+
84
+ // src/shared/version.ts
85
+ var VERSION = package_default.version;
86
+ var PACKAGE_NAME = package_default.name;
87
+
88
+ export {
89
+ BRAND_NAME,
90
+ SERVER_NAME,
91
+ MERCHANT_ENTITY,
92
+ SERVER_TITLE,
93
+ SERVER_WEBSITE_URL,
94
+ SERVER_ICONS,
95
+ VERSION,
96
+ PACKAGE_NAME
97
+ };
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ PACKAGE_NAME
4
+ } from "./chunk-3OSHCYWX.js";
5
+
6
+ // src/shared/cli-invoke.ts
7
+ var CLI_INVOKE = `npx ${PACKAGE_NAME}`;
8
+
9
+ export {
10
+ CLI_INVOKE
11
+ };
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ log
4
+ } from "./chunk-2UUMFH2N.js";
5
+
6
+ // src/stdio/credential-store.ts
7
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
8
+ import { homedir } from "os";
9
+ import { join } from "path";
10
+ var KEYCHAIN_SERVICE = "lune-mcp";
11
+ var KEYCHAIN_ACCOUNT = "default";
12
+ var NO_STORE_HINT = [
13
+ "No usable credential store: login cannot save the refresh token securely. Three options:",
14
+ " 1) Install a system keychain / Secret Service (macOS Keychain / Windows Credential Manager / Linux libsecret);",
15
+ " 2) Skip login and use the LUNE_MCP_TOKEN environment variable instead (a user JWT valid for 24h, escape hatch);",
16
+ " 3) Explicitly accept plaintext on disk: set LUNE_MCP_ALLOW_FILE_CREDENTIALS=1 (writes ~/.lune-mcp/credentials.json, mode 0600)."
17
+ ].join("\n");
18
+ function parseStored(raw) {
19
+ try {
20
+ const data = JSON.parse(raw);
21
+ if (typeof data.refresh_token !== "string" || !data.refresh_token) return null;
22
+ return {
23
+ refresh_token: data.refresh_token,
24
+ user_id: typeof data.user_id === "string" ? data.user_id : "",
25
+ is_supplier: data.is_supplier === true,
26
+ scopes: typeof data.scopes === "string" ? data.scopes : "",
27
+ obtained_at: typeof data.obtained_at === "string" ? data.obtained_at : ""
28
+ };
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ function metaOf(creds) {
34
+ if (!creds) return null;
35
+ return { user_id: creds.user_id, is_supplier: creds.is_supplier, scopes: creds.scopes };
36
+ }
37
+ var defaultEntryFactory = async (service, account) => {
38
+ const { AsyncEntry } = await import("@napi-rs/keyring");
39
+ return new AsyncEntry(service, account);
40
+ };
41
+ var KeychainStore = class {
42
+ kind = "keychain";
43
+ entryFactory;
44
+ constructor(entryFactory = defaultEntryFactory) {
45
+ this.entryFactory = entryFactory;
46
+ }
47
+ /** 读写探针:headless Linux 常见「装得上但用不了」(docs/03 §5.2),必须真写一次。 */
48
+ async probe() {
49
+ try {
50
+ const entry = await this.entryFactory(KEYCHAIN_SERVICE, "__probe__");
51
+ await entry.setPassword("probe");
52
+ const got = await entry.getPassword();
53
+ await entry.deleteCredential();
54
+ return got === "probe";
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ entry() {
60
+ return this.entryFactory(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
61
+ }
62
+ async read() {
63
+ try {
64
+ const raw = await (await this.entry()).getPassword();
65
+ return raw ? parseStored(raw) : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ async write(creds) {
71
+ await (await this.entry()).setPassword(JSON.stringify(creds));
72
+ }
73
+ async delete() {
74
+ try {
75
+ await (await this.entry()).deleteCredential();
76
+ } catch {
77
+ }
78
+ }
79
+ async readMeta() {
80
+ return metaOf(await this.read());
81
+ }
82
+ };
83
+ var FileStore = class {
84
+ kind = "file";
85
+ path;
86
+ dir;
87
+ constructor(dir = join(homedir(), ".lune-mcp")) {
88
+ this.dir = dir;
89
+ this.path = join(dir, "credentials.json");
90
+ log.warn(
91
+ `LUNE_MCP_ALLOW_FILE_CREDENTIALS=1: the refresh token will be stored in PLAINTEXT at ${this.path} (mode 0600). Switch to a system keychain as soon as possible.`
92
+ );
93
+ }
94
+ async read() {
95
+ try {
96
+ return parseStored(readFileSync(this.path, "utf8"));
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ async write(creds) {
102
+ mkdirSync(this.dir, { recursive: true, mode: 448 });
103
+ writeFileSync(this.path, JSON.stringify(creds, null, 2), { mode: 384 });
104
+ chmodSync(this.path, 384);
105
+ }
106
+ async delete() {
107
+ rmSync(this.path, { force: true });
108
+ }
109
+ async readMeta() {
110
+ return metaOf(await this.read());
111
+ }
112
+ };
113
+ async function openCredentialStore(opts = {}) {
114
+ const keychain = new KeychainStore(opts.entryFactory);
115
+ if (await keychain.probe()) return keychain;
116
+ const env = opts.env ?? process.env;
117
+ if (env.LUNE_MCP_ALLOW_FILE_CREDENTIALS === "1") return new FileStore(opts.fileDir);
118
+ return null;
119
+ }
120
+
121
+ export {
122
+ NO_STORE_HINT,
123
+ KeychainStore,
124
+ openCredentialStore
125
+ };
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ probeIdentity
4
+ } from "./chunk-MC3S3YL6.js";
5
+ import {
6
+ BackendClient,
7
+ log
8
+ } from "./chunk-2UUMFH2N.js";
9
+ import {
10
+ CLI_INVOKE
11
+ } from "./chunk-4UMZU6R2.js";
12
+ import {
13
+ BRAND_NAME
14
+ } from "./chunk-3OSHCYWX.js";
15
+
16
+ // src/stdio/oauth-login.ts
17
+ import { createHash, randomBytes } from "crypto";
18
+ import { createServer } from "http";
19
+ var CLI_CLIENT_ID = "mcp-cli";
20
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
21
+ var HTTP_TIMEOUT_MS = 3e4;
22
+ function assertOpenableUrl(url) {
23
+ let parsed;
24
+ try {
25
+ parsed = new URL(url);
26
+ } catch {
27
+ throw new Error(`Refusing to open invalid URL: ${url.slice(0, 100)}`);
28
+ }
29
+ const loopbackHttp = parsed.protocol === "http:" && (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost");
30
+ if (parsed.protocol !== "https:" && !loopbackHttp) {
31
+ throw new Error(
32
+ `Refusing to open a non-https authorization URL (${parsed.protocol}//\u2026) \u2014 only https: or loopback http: is allowed (lesson of CVE-2025-6514).`
33
+ );
34
+ }
35
+ }
36
+ var RESULT_PATH_OK = "/cli-login/complete";
37
+ var RESULT_PATH_FAILED = "/cli-login/failed";
38
+ function resultPageOrigin(asIssuer) {
39
+ let u;
40
+ try {
41
+ u = new URL(asIssuer);
42
+ } catch {
43
+ return null;
44
+ }
45
+ const loopbackHttp = u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost");
46
+ if (u.protocol !== "https:" && !loopbackHttp) return null;
47
+ return u.origin;
48
+ }
49
+ function failReasonForOAuthError(error) {
50
+ if (error === "access_denied") return "denied";
51
+ if (error === "temporarily_unavailable") return "busy";
52
+ return "server";
53
+ }
54
+ function metadataUrlsFor(issuer) {
55
+ const u = new URL(issuer);
56
+ const path = u.pathname.replace(/\/+$/, "");
57
+ const primary = `${u.origin}/.well-known/oauth-authorization-server${path === "/" ? "" : path}`;
58
+ if (path === "" || path === "/") return [primary];
59
+ return [primary, `${u.origin}${path}/.well-known/oauth-authorization-server`];
60
+ }
61
+ async function runLoginFlow(opts) {
62
+ const asIssuer = opts.asIssuer.replace(/\/+$/, "");
63
+ const fetchImpl = opts.fetchImpl ?? fetch;
64
+ const print = opts.print ?? ((msg) => process.stderr.write(`${msg}
65
+ `));
66
+ const timeoutMs = opts.timeoutMs ?? LOGIN_TIMEOUT_MS;
67
+ let meta = null;
68
+ const attempts = [];
69
+ for (const metaUrl of metadataUrlsFor(asIssuer)) {
70
+ const metaRes = await fetchImpl(metaUrl, {
71
+ headers: { accept: "application/json" },
72
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
73
+ });
74
+ if (metaRes.ok) {
75
+ meta = await metaRes.json();
76
+ break;
77
+ }
78
+ attempts.push(`${metaUrl} \u2192 HTTP ${metaRes.status}`);
79
+ }
80
+ if (!meta) {
81
+ throw new Error(
82
+ `Failed to fetch AS metadata (issuer=${asIssuer}):
83
+ ${attempts.join("\n ")}
84
+ If you set LUNE_MCP_AS_ISSUER yourself, check that the /oauth path prefix is not missing.`
85
+ );
86
+ }
87
+ if (meta.issuer !== asIssuer) {
88
+ throw new Error(`AS issuer mismatch: expected ${asIssuer}, metadata declares ${meta.issuer}`);
89
+ }
90
+ const server = createServer();
91
+ await new Promise((resolve, reject) => {
92
+ server.once("error", reject);
93
+ server.listen(0, "127.0.0.1", resolve);
94
+ });
95
+ const port = server.address().port;
96
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
97
+ const verifier = randomBytes(32).toString("base64url");
98
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
99
+ const state = randomBytes(16).toString("base64url");
100
+ try {
101
+ const authorizeUrl = new URL(meta.authorization_endpoint);
102
+ authorizeUrl.searchParams.set("response_type", "code");
103
+ authorizeUrl.searchParams.set("client_id", CLI_CLIENT_ID);
104
+ authorizeUrl.searchParams.set("redirect_uri", redirectUri);
105
+ authorizeUrl.searchParams.set("code_challenge", challenge);
106
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
107
+ authorizeUrl.searchParams.set("state", state);
108
+ assertOpenableUrl(authorizeUrl.toString());
109
+ const callbackPromise = waitForCallback(server, {
110
+ state,
111
+ asIssuer,
112
+ resultOrigin: resultPageOrigin(asIssuer)
113
+ });
114
+ void callbackPromise.catch(() => {
115
+ });
116
+ if (opts.noBrowser) {
117
+ print(`Open this URL in your browser to sign in:
118
+
119
+ ${authorizeUrl}
120
+ `);
121
+ } else {
122
+ const openBrowser = opts.openBrowser ?? (async (url) => {
123
+ const { default: open } = await import("open");
124
+ await open(url);
125
+ });
126
+ try {
127
+ print("Opening your browser to sign in\u2026");
128
+ await openBrowser(authorizeUrl.toString());
129
+ } catch (err) {
130
+ print(
131
+ `Could not open the browser automatically (${err instanceof Error ? err.message : String(err)}). Open this URL manually:
132
+
133
+ ${authorizeUrl}
134
+ `
135
+ );
136
+ }
137
+ }
138
+ const code = await withTimeout(
139
+ callbackPromise,
140
+ timeoutMs,
141
+ "Timed out waiting for browser authorization (5 minutes)"
142
+ );
143
+ const tokenRes = await fetchImpl(meta.token_endpoint, {
144
+ method: "POST",
145
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
146
+ body: new URLSearchParams({
147
+ grant_type: "authorization_code",
148
+ code,
149
+ code_verifier: verifier,
150
+ client_id: CLI_CLIENT_ID,
151
+ redirect_uri: redirectUri
152
+ }).toString(),
153
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
154
+ });
155
+ if (!tokenRes.ok) {
156
+ const body = await tokenRes.text().catch(() => "");
157
+ throw new Error(`Token exchange failed: HTTP ${tokenRes.status} ${body.slice(0, 200)}`);
158
+ }
159
+ const tokens = await tokenRes.json();
160
+ if (!tokens.access_token || !tokens.refresh_token) {
161
+ throw new Error("Token response is missing access_token/refresh_token");
162
+ }
163
+ const backend = new BackendClient({
164
+ baseUrl: opts.apiBase,
165
+ fetchImpl,
166
+ credentials: {
167
+ getAccessToken: async () => tokens.access_token,
168
+ forceRefresh: async () => null,
169
+ reauthHint: () => `The temporary credentials from this login flow expired. Run \`${CLI_INVOKE} login\` again.`
170
+ }
171
+ });
172
+ const identity = await probeIdentity(backend);
173
+ const scopes = tokens.scopes ?? tokens.scope ?? "";
174
+ await opts.store.write({
175
+ refresh_token: tokens.refresh_token,
176
+ user_id: identity.userId,
177
+ is_supplier: identity.isSupplier,
178
+ scopes,
179
+ obtained_at: (/* @__PURE__ */ new Date()).toISOString()
180
+ });
181
+ return { userId: identity.userId, isSupplier: identity.isSupplier, scopes };
182
+ } finally {
183
+ server.close();
184
+ server.closeAllConnections?.();
185
+ }
186
+ }
187
+ function waitForCallback(server, expect) {
188
+ return new Promise((resolve, reject) => {
189
+ server.on("request", (req, res) => {
190
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
191
+ if (url.pathname !== "/callback") {
192
+ res.writeHead(404).end();
193
+ return;
194
+ }
195
+ const land = (outcome) => {
196
+ if (expect.resultOrigin) {
197
+ const location = outcome.ok ? `${expect.resultOrigin}${RESULT_PATH_OK}` : `${expect.resultOrigin}${RESULT_PATH_FAILED}?reason=${outcome.reason}`;
198
+ res.writeHead(302, { location, "cache-control": "no-store" });
199
+ res.end();
200
+ return;
201
+ }
202
+ res.writeHead(outcome.ok ? 200 : 400, { "content-type": "text/html; charset=utf-8" });
203
+ res.end(
204
+ outcome.ok ? `<html><head><title>Signed in \xB7 ${BRAND_NAME}</title></head><body><p>Signed in to the ${BRAND_NAME} CLI. You can close this tab and return to the terminal.</p></body></html>` : `<html><head><title>Sign-in failed \xB7 ${BRAND_NAME}</title></head><body><p>${BRAND_NAME} CLI sign-in failed. Return to the terminal for details.</p></body></html>`
205
+ );
206
+ };
207
+ const fail = (reason, why) => {
208
+ land({ ok: false, reason });
209
+ reject(new Error(why));
210
+ };
211
+ const error = url.searchParams.get("error");
212
+ if (error) {
213
+ fail(
214
+ failReasonForOAuthError(error),
215
+ `Authorization denied: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`
216
+ );
217
+ return;
218
+ }
219
+ const state = url.searchParams.get("state");
220
+ if (state !== expect.state) {
221
+ fail("mismatch", "state mismatch (possible CSRF or a crossed callback); rejected");
222
+ return;
223
+ }
224
+ const iss = url.searchParams.get("iss");
225
+ if (iss !== expect.asIssuer) {
226
+ fail(
227
+ "mismatch",
228
+ `Authorization response iss mismatch (expected ${expect.asIssuer}, got ${iss ?? "missing"}); rejected`
229
+ );
230
+ return;
231
+ }
232
+ const code = url.searchParams.get("code");
233
+ if (!code) {
234
+ fail("server", "Authorization response is missing code");
235
+ return;
236
+ }
237
+ land({ ok: true });
238
+ resolve(code);
239
+ });
240
+ });
241
+ }
242
+ async function withTimeout(promise, ms, message) {
243
+ let timer;
244
+ try {
245
+ return await Promise.race([
246
+ promise,
247
+ new Promise((_, reject) => {
248
+ timer = setTimeout(() => reject(new Error(message)), ms);
249
+ })
250
+ ]);
251
+ } finally {
252
+ clearTimeout(timer);
253
+ }
254
+ }
255
+ async function runLogout(opts) {
256
+ const fetchImpl = opts.fetchImpl ?? fetch;
257
+ const print = opts.print ?? ((msg) => process.stderr.write(`${msg}
258
+ `));
259
+ const creds = await opts.store.read();
260
+ if (creds) {
261
+ try {
262
+ await fetchImpl(`${opts.apiBase.replace(/\/+$/, "")}/v1/auth/revoke`, {
263
+ method: "POST",
264
+ headers: { "content-type": "application/json" },
265
+ body: JSON.stringify({ refresh_token: creds.refresh_token }),
266
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
267
+ });
268
+ } catch (err) {
269
+ log.warn(
270
+ "Server-side revocation failed (ignored; local credentials will still be cleared):",
271
+ err instanceof Error ? err.message : err
272
+ );
273
+ }
274
+ }
275
+ await opts.store.delete();
276
+ print(
277
+ creds ? "Signed out: local credentials cleared; refresh token revocation requested." : "No saved credentials on this machine."
278
+ );
279
+ }
280
+
281
+ export {
282
+ CLI_CLIENT_ID,
283
+ assertOpenableUrl,
284
+ resultPageOrigin,
285
+ failReasonForOAuthError,
286
+ metadataUrlsFor,
287
+ runLoginFlow,
288
+ runLogout
289
+ };
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/backend/identity.ts
4
+ async function probeIdentity(backend) {
5
+ const self = await backend.get("/v1/auth/self");
6
+ return { userId: self.id, isSupplier: self.is_supplier };
7
+ }
8
+
9
+ export {
10
+ probeIdentity
11
+ };