@zenlayer/lune-mcp 0.0.0-stage → 1.2.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,403 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CLI_INVOKE
4
+ } from "./chunk-G7ZX5GSF.js";
5
+ import {
6
+ BRAND_NAME,
7
+ PACKAGE_NAME
8
+ } from "./chunk-NN23AOUC.js";
9
+
10
+ // src/cli/install/types.ts
11
+ import { execFile as execFileCb } from "child_process";
12
+ import { promisify } from "util";
13
+ var execFileP = promisify(execFileCb);
14
+ var defaultExecFile = async (cmd, args) => {
15
+ const { stdout, stderr } = await execFileP(cmd, args, { timeout: 3e4 });
16
+ return { stdout: String(stdout), stderr: String(stderr) };
17
+ };
18
+ function stdioCommand(platform = process.platform) {
19
+ if (platform === "win32") {
20
+ return { command: "cmd", args: ["/c", "npx", "-y", `${PACKAGE_NAME}@1`, "mcp"] };
21
+ }
22
+ return { command: "npx", args: ["-y", `${PACKAGE_NAME}@1`, "mcp"] };
23
+ }
24
+ async function tryExec(execFile, cmd, args) {
25
+ try {
26
+ await execFile(cmd, args);
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+ async function probeBinary(execFile, bin) {
33
+ try {
34
+ await execFile(bin, ["--version"]);
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ // src/cli/install/clients/claude-code.ts
42
+ function claudeCodeAdapter(deps = {}) {
43
+ const execFile = deps.execFile ?? defaultExecFile;
44
+ return {
45
+ id: "claude-code",
46
+ label: "Claude Code",
47
+ strategy: "cli",
48
+ capabilities: { remote: true, projectScope: true },
49
+ detect: () => probeBinary(execFile, "claude"),
50
+ async install(spec) {
51
+ const removed = [];
52
+ for (const s of ["local", "project", "user"]) {
53
+ if (await tryExec(execFile, "claude", ["mcp", "remove", spec.serverName, "-s", s])) removed.push(s);
54
+ }
55
+ const cleaned = removed.length > 0 ? `; cleared previous config (${removed.join("/")} scope)` : "";
56
+ const json = spec.transport === "remote" ? JSON.stringify({ type: "http", url: spec.url }) : JSON.stringify({ type: "stdio", command: spec.command, args: spec.args });
57
+ try {
58
+ await execFile("claude", ["mcp", "add-json", spec.serverName, json, "--scope", spec.scope]);
59
+ return {
60
+ ok: true,
61
+ detail: `claude mcp add-json ${spec.serverName} (${spec.scope} scope) done${cleaned}`
62
+ };
63
+ } catch (err) {
64
+ return {
65
+ ok: false,
66
+ detail: `claude mcp add-json failed: ${err instanceof Error ? err.message : String(err)}`
67
+ };
68
+ }
69
+ }
70
+ };
71
+ }
72
+
73
+ // src/cli/install/clients/claude-desktop.ts
74
+ import { existsSync } from "fs";
75
+ import { homedir } from "os";
76
+ import { dirname as dirname2, join } from "path";
77
+
78
+ // src/cli/install/file-writer.ts
79
+ import { closeSync, copyFileSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from "fs";
80
+ import { readFile } from "fs/promises";
81
+ import { dirname } from "path";
82
+ async function writeMcpEntry(opts) {
83
+ let base = {};
84
+ let existed = false;
85
+ try {
86
+ const raw = await readFile(opts.filePath, "utf8");
87
+ existed = true;
88
+ try {
89
+ const parsed = JSON.parse(raw);
90
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
91
+ return {
92
+ ok: false,
93
+ changed: false,
94
+ detail: `Config file is not a JSON object (${opts.filePath}); aborted without changes \u2014 please fix it manually.`
95
+ };
96
+ }
97
+ base = parsed;
98
+ } catch {
99
+ return {
100
+ ok: false,
101
+ changed: false,
102
+ detail: `Config file is corrupted and cannot be parsed as JSON (${opts.filePath}); aborted without changes \u2014 please fix it manually.`
103
+ };
104
+ }
105
+ } catch {
106
+ }
107
+ const container = base[opts.topKey];
108
+ if (container !== void 0 && (typeof container !== "object" || container === null || Array.isArray(container))) {
109
+ return {
110
+ ok: false,
111
+ changed: false,
112
+ detail: `${opts.topKey} is not an object (${opts.filePath}); aborted without changes \u2014 please fix it manually.`
113
+ };
114
+ }
115
+ const servers = { ...container ?? {} };
116
+ if (JSON.stringify(servers[opts.serverName]) === JSON.stringify(opts.entry)) {
117
+ return { ok: true, changed: false, detail: `already up to date (${opts.filePath})` };
118
+ }
119
+ servers[opts.serverName] = opts.entry;
120
+ const next = { ...base, [opts.topKey]: servers };
121
+ atomicWriteJson(opts.filePath, next, existed);
122
+ return { ok: true, changed: true, detail: `wrote ${opts.filePath} (previous file backed up as .bak)` };
123
+ }
124
+ function atomicWriteJson(filePath, obj, existed) {
125
+ mkdirSync(dirname(filePath), { recursive: true });
126
+ const tmp = `${filePath}.tmp`;
127
+ const fd = openSync(tmp, "w");
128
+ try {
129
+ writeSync(fd, `${JSON.stringify(obj, null, 2)}
130
+ `);
131
+ fsyncSync(fd);
132
+ } finally {
133
+ closeSync(fd);
134
+ }
135
+ if (existed) copyFileSync(filePath, `${filePath}.bak`);
136
+ renameSync(tmp, filePath);
137
+ }
138
+ async function removeMcpEntry(opts) {
139
+ let raw;
140
+ try {
141
+ raw = await readFile(opts.filePath, "utf8");
142
+ } catch {
143
+ return { ok: true, changed: false, detail: `no stale config (${opts.filePath} does not exist)` };
144
+ }
145
+ let base;
146
+ try {
147
+ const parsed = JSON.parse(raw);
148
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
149
+ return {
150
+ ok: false,
151
+ changed: false,
152
+ detail: `Config file is not a JSON object (${opts.filePath}); stale entry not removed \u2014 please check manually.`
153
+ };
154
+ }
155
+ base = parsed;
156
+ } catch {
157
+ return {
158
+ ok: false,
159
+ changed: false,
160
+ detail: `Config file is corrupted and cannot be parsed as JSON (${opts.filePath}); stale entry not removed \u2014 please check manually.`
161
+ };
162
+ }
163
+ const container = base[opts.topKey];
164
+ if (typeof container !== "object" || container === null || Array.isArray(container)) {
165
+ return { ok: true, changed: false, detail: `no stale config (${opts.filePath})` };
166
+ }
167
+ const servers = container;
168
+ if (!(opts.serverName in servers)) {
169
+ return { ok: true, changed: false, detail: `no stale config (${opts.filePath})` };
170
+ }
171
+ const nextServers = { ...servers };
172
+ delete nextServers[opts.serverName];
173
+ atomicWriteJson(opts.filePath, { ...base, [opts.topKey]: nextServers }, true);
174
+ return { ok: true, changed: true, detail: `removed stale config (${opts.filePath})` };
175
+ }
176
+
177
+ // src/cli/install/clients/claude-desktop.ts
178
+ function claudeDesktopConfigPath(platform, home, env = process.env) {
179
+ if (platform === "darwin") {
180
+ return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
181
+ }
182
+ if (platform === "win32") {
183
+ const appData = env.APPDATA || join(home, "AppData", "Roaming");
184
+ return join(appData, "Claude", "claude_desktop_config.json");
185
+ }
186
+ return join(home, ".config", "Claude", "claude_desktop_config.json");
187
+ }
188
+ function claudeDesktopAdapter(deps = {}) {
189
+ const home = deps.homeDir ?? homedir();
190
+ const platform = deps.platform ?? process.platform;
191
+ const configPath = claudeDesktopConfigPath(platform, home, deps.env ?? process.env);
192
+ return {
193
+ id: "claude-desktop",
194
+ label: "Claude Desktop",
195
+ strategy: "file",
196
+ configPath,
197
+ // remote 走应用内 Connectors UI(配置文件只认 stdio command);无项目级配置。
198
+ // 刻意不静默回落 stdio:回落会引入隐藏的 login 要求,与「装的是 remote」的预期不符。
199
+ capabilities: { remote: false, projectScope: false },
200
+ manualHint(spec) {
201
+ if (spec.transport === "remote") {
202
+ return `Claude Desktop's config file does not support remote MCP. Two options: \u2460 in-app Settings \u2192 Connectors \u2192 Add custom connector \u2014 Name: ${BRAND_NAME}, URL: ${spec.url}; \u2461 install the local mode instead: ${CLI_INVOKE} install claude-desktop --stdio`;
203
+ }
204
+ return "Claude Desktop only has a global config file (no project concept) \u2014 use --scope user instead.";
205
+ },
206
+ detect: async () => existsSync(dirname2(configPath)),
207
+ async install(spec) {
208
+ if (spec.transport !== "stdio") {
209
+ return {
210
+ ok: false,
211
+ detail: "Internal error: Claude Desktop supports stdio only (should have been blocked by the capability gate)"
212
+ };
213
+ }
214
+ const result = await writeMcpEntry({
215
+ filePath: configPath,
216
+ topKey: "mcpServers",
217
+ serverName: spec.serverName,
218
+ entry: { command: spec.command, args: spec.args }
219
+ });
220
+ return { ok: result.ok, detail: result.detail };
221
+ }
222
+ };
223
+ }
224
+
225
+ // src/cli/install/clients/codex.ts
226
+ function codexAdapter(deps = {}) {
227
+ const execFile = deps.execFile ?? defaultExecFile;
228
+ return {
229
+ id: "codex",
230
+ label: "Codex CLI",
231
+ strategy: "cli",
232
+ capabilities: { remote: true, projectScope: false },
233
+ // config.toml 全局,mcp add 无项目级选项
234
+ manualHint: () => "Codex CLI stores MCP config in a global config.toml; `codex mcp add` has no project-scope option \u2014 use --scope user, or configure project scope manually per the Codex docs.",
235
+ detect: () => probeBinary(execFile, "codex"),
236
+ async install(spec) {
237
+ const removed = await tryExec(execFile, "codex", ["mcp", "remove", spec.serverName]);
238
+ const cleaned = removed ? "; cleared previous config" : "";
239
+ const args = spec.transport === "remote" ? ["mcp", "add", spec.serverName, "--url", spec.url] : ["mcp", "add", spec.serverName, "--", spec.command, ...spec.args];
240
+ try {
241
+ await execFile("codex", args);
242
+ return { ok: true, detail: `codex mcp add done${cleaned}` };
243
+ } catch (err) {
244
+ return {
245
+ ok: false,
246
+ detail: `codex mcp add failed: ${err instanceof Error ? err.message : String(err)}`
247
+ };
248
+ }
249
+ }
250
+ };
251
+ }
252
+
253
+ // src/cli/install/clients/cursor.ts
254
+ import { existsSync as existsSync2 } from "fs";
255
+ import { homedir as homedir2 } from "os";
256
+ import { join as join2 } from "path";
257
+ function cursorAdapter(deps = {}) {
258
+ const home = deps.homeDir ?? homedir2();
259
+ const cwd = deps.cwd ?? process.cwd();
260
+ const configPath = join2(home, ".cursor", "mcp.json");
261
+ return {
262
+ id: "cursor",
263
+ label: "Cursor",
264
+ strategy: "file",
265
+ configPath,
266
+ capabilities: { remote: true, projectScope: true },
267
+ detect: async () => existsSync2(join2(home, ".cursor")),
268
+ async install(spec) {
269
+ const projectPath = join2(cwd, ".cursor", "mcp.json");
270
+ const target = spec.scope === "project" ? projectPath : configPath;
271
+ const other = spec.scope === "project" ? configPath : projectPath;
272
+ const result = await writeMcpEntry({
273
+ filePath: target,
274
+ topKey: "mcpServers",
275
+ serverName: spec.serverName,
276
+ entry: spec.transport === "remote" ? { url: spec.url } : { command: spec.command, args: spec.args }
277
+ });
278
+ if (!result.ok) return { ok: false, detail: result.detail };
279
+ const cleanup = await removeMcpEntry({
280
+ filePath: other,
281
+ topKey: "mcpServers",
282
+ serverName: spec.serverName
283
+ });
284
+ const cleaned = cleanup.changed ? `; ${cleanup.detail}` : cleanup.ok ? "" : `; \u26A0\uFE0F ${cleanup.detail}`;
285
+ return { ok: true, detail: `${result.detail}${cleaned}` };
286
+ }
287
+ };
288
+ }
289
+
290
+ // src/cli/install/clients/gemini.ts
291
+ function geminiAdapter(deps = {}) {
292
+ const execFile = deps.execFile ?? defaultExecFile;
293
+ return {
294
+ id: "gemini",
295
+ label: "Gemini CLI",
296
+ strategy: "cli",
297
+ capabilities: { remote: true, projectScope: true },
298
+ detect: () => probeBinary(execFile, "gemini"),
299
+ async install(spec) {
300
+ const removed = [];
301
+ for (const s of ["user", "project"]) {
302
+ if (await tryExec(execFile, "gemini", ["mcp", "remove", "-s", s, spec.serverName])) removed.push(s);
303
+ }
304
+ const cleaned = removed.length > 0 ? `; cleared previous config (${removed.join("/")} scope)` : "";
305
+ const args = spec.transport === "remote" ? ["mcp", "add", "-s", spec.scope, "-t", "http", spec.serverName, spec.url] : ["mcp", "add", "-s", spec.scope, spec.serverName, spec.command, ...spec.args];
306
+ try {
307
+ await execFile("gemini", args);
308
+ return { ok: true, detail: `gemini mcp add done${cleaned}` };
309
+ } catch (err) {
310
+ return {
311
+ ok: false,
312
+ detail: `gemini mcp add failed: ${err instanceof Error ? err.message : String(err)}`
313
+ };
314
+ }
315
+ }
316
+ };
317
+ }
318
+
319
+ // src/cli/install/clients/vscode.ts
320
+ import { readFileSync } from "fs";
321
+ import { homedir as homedir3 } from "os";
322
+ import { join as join3 } from "path";
323
+ function vscodeUserMcpPath(platform, home, env = process.env) {
324
+ if (platform === "darwin") return join3(home, "Library", "Application Support", "Code", "User", "mcp.json");
325
+ if (platform === "win32") {
326
+ const appData = env.APPDATA || join3(home, "AppData", "Roaming");
327
+ return join3(appData, "Code", "User", "mcp.json");
328
+ }
329
+ return join3(home, ".config", "Code", "User", "mcp.json");
330
+ }
331
+ function hasUserEntry(path, serverName) {
332
+ try {
333
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
334
+ return typeof parsed?.servers === "object" && parsed.servers !== null && serverName in parsed.servers;
335
+ } catch {
336
+ return false;
337
+ }
338
+ }
339
+ function vscodeAdapter(deps = {}) {
340
+ const execFile = deps.execFile ?? defaultExecFile;
341
+ const cwd = deps.cwd ?? process.cwd();
342
+ const home = deps.homeDir ?? homedir3();
343
+ const platform = deps.platform ?? process.platform;
344
+ const userMcpPath = vscodeUserMcpPath(platform, home, deps.env ?? process.env);
345
+ return {
346
+ id: "vscode",
347
+ label: "VS Code",
348
+ strategy: "cli",
349
+ capabilities: { remote: true, projectScope: true },
350
+ detect: () => probeBinary(execFile, "code"),
351
+ async install(spec) {
352
+ const projectPath = join3(cwd, ".vscode", "mcp.json");
353
+ if (spec.scope === "project") {
354
+ const result = await writeMcpEntry({
355
+ filePath: projectPath,
356
+ topKey: "servers",
357
+ serverName: spec.serverName,
358
+ entry: spec.transport === "remote" ? { type: "http", url: spec.url } : { type: "stdio", command: spec.command, args: spec.args }
359
+ });
360
+ if (!result.ok) return { ok: false, detail: result.detail };
361
+ const stale = hasUserEntry(userMcpPath, spec.serverName) ? `; \u26A0\uFE0F A previous user-level ${spec.serverName} entry may still exist. Remove it in VS Code: Command Palette \u2192 "MCP: Open User Configuration".` : "";
362
+ return { ok: true, detail: `${result.detail}${stale}` };
363
+ }
364
+ const json = spec.transport === "remote" ? JSON.stringify({ name: spec.serverName, type: "http", url: spec.url }) : JSON.stringify({ name: spec.serverName, command: spec.command, args: spec.args });
365
+ try {
366
+ await execFile("code", ["--add-mcp", json]);
367
+ const cleanup = await removeMcpEntry({
368
+ filePath: projectPath,
369
+ topKey: "servers",
370
+ serverName: spec.serverName
371
+ });
372
+ const cleaned = cleanup.changed ? `; ${cleanup.detail}` : cleanup.ok ? "" : `; \u26A0\uFE0F ${cleanup.detail}`;
373
+ return { ok: true, detail: `code --add-mcp done${cleaned}` };
374
+ } catch (err) {
375
+ return {
376
+ ok: false,
377
+ detail: `code --add-mcp failed: ${err instanceof Error ? err.message : String(err)}`
378
+ };
379
+ }
380
+ }
381
+ };
382
+ }
383
+
384
+ // src/cli/install/registry.ts
385
+ function allAdapters(deps = {}) {
386
+ return [
387
+ claudeCodeAdapter(deps),
388
+ vscodeAdapter(deps),
389
+ codexAdapter(deps),
390
+ geminiAdapter(deps),
391
+ cursorAdapter(deps),
392
+ claudeDesktopAdapter(deps)
393
+ ];
394
+ }
395
+ function findAdapter(id, deps = {}) {
396
+ return allAdapters(deps).find((a) => a.id === id);
397
+ }
398
+
399
+ export {
400
+ stdioCommand,
401
+ allAdapters,
402
+ findAdapter
403
+ };
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ PACKAGE_NAME
4
+ } from "./chunk-NN23AOUC.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,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
+ };
@@ -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.2.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,158 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ log
4
+ } from "./chunk-TFX4RC2N.js";
5
+ import {
6
+ CLI_INVOKE
7
+ } from "./chunk-G7ZX5GSF.js";
8
+
9
+ // src/stdio/credential-provider.ts
10
+ import { closeSync, mkdirSync, openSync, rmSync, statSync, writeSync } from "fs";
11
+ import { homedir } from "os";
12
+ import { dirname, join } from "path";
13
+ var EXP_SKEW_MS = 3e5;
14
+ var REFRESH_TIMEOUT_MS = 3e4;
15
+ var REAUTH_HINT = `Your session has expired or been revoked. Run \`${CLI_INVOKE} login\` to sign in again (or set the LUNE_MCP_TOKEN environment variable as a temporary fallback).`;
16
+ function decodeJwtExpMs(jwt) {
17
+ try {
18
+ const payload = jwt.split(".")[1];
19
+ if (!payload) return null;
20
+ const data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
21
+ return typeof data.exp === "number" ? data.exp * 1e3 : null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+ var KeychainCredentialProvider = class {
27
+ store;
28
+ apiBase;
29
+ fetchImpl;
30
+ lockPath;
31
+ lockPollMs;
32
+ lockStaleMs;
33
+ now;
34
+ cached = null;
35
+ /** 进程内单飞:并发 getAccessToken 共享同一次 refresh。 */
36
+ inflight = null;
37
+ constructor(opts) {
38
+ this.store = opts.store;
39
+ this.apiBase = opts.apiBase.replace(/\/+$/, "");
40
+ this.fetchImpl = opts.fetchImpl ?? fetch;
41
+ this.lockPath = opts.lockPath ?? join(homedir(), ".lune-mcp", "refresh.lock");
42
+ this.lockPollMs = opts.lockPollMs ?? 200;
43
+ this.lockStaleMs = opts.lockStaleMs ?? 3e4;
44
+ this.now = opts.nowFn ?? Date.now;
45
+ }
46
+ async getAccessToken() {
47
+ if (this.cached && this.now() < this.cached.expMs - EXP_SKEW_MS) {
48
+ return this.cached.jwt;
49
+ }
50
+ return this.refreshShared();
51
+ }
52
+ async forceRefresh() {
53
+ this.cached = null;
54
+ return this.refreshShared();
55
+ }
56
+ reauthHint() {
57
+ return REAUTH_HINT;
58
+ }
59
+ refreshShared() {
60
+ if (!this.inflight) {
61
+ this.inflight = this.refresh().finally(() => {
62
+ this.inflight = null;
63
+ });
64
+ }
65
+ return this.inflight;
66
+ }
67
+ async refresh() {
68
+ const before = await this.store.read();
69
+ if (!before) return null;
70
+ const release = await this.acquireLock();
71
+ try {
72
+ const current = await this.store.read() ?? before;
73
+ const response = await this.callRefresh(current.refresh_token);
74
+ if (response === null) {
75
+ this.cached = null;
76
+ return null;
77
+ }
78
+ await this.store.write({
79
+ ...current,
80
+ refresh_token: response.refresh_token,
81
+ scopes: response.scopes ?? current.scopes,
82
+ obtained_at: new Date(this.now()).toISOString()
83
+ });
84
+ const expMs = typeof response.expires_in === "number" ? this.now() + response.expires_in * 1e3 : decodeJwtExpMs(response.access_token) ?? this.now() + 36e5;
85
+ this.cached = { jwt: response.access_token, expMs };
86
+ return response.access_token;
87
+ } finally {
88
+ release();
89
+ }
90
+ }
91
+ /** null = 链死(401);抛错 = 网络等瞬时故障(向上冒泡为 ApiError 语义由调用方处理)。 */
92
+ async callRefresh(refreshToken) {
93
+ let res;
94
+ try {
95
+ res = await this.fetchImpl(`${this.apiBase}/v1/auth/refresh`, {
96
+ method: "POST",
97
+ headers: { "content-type": "application/json", accept: "application/json" },
98
+ body: JSON.stringify({ refresh_token: refreshToken }),
99
+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS)
100
+ });
101
+ } catch (err) {
102
+ log.warn(
103
+ "Refresh request failed (network/timeout); treating as no credentials for this call:",
104
+ err instanceof Error ? err.message : err
105
+ );
106
+ return null;
107
+ }
108
+ if (res.status === 401) return null;
109
+ if (!res.ok) {
110
+ log.warn(`Unexpected refresh status ${res.status}; treating as no credentials for this call`);
111
+ return null;
112
+ }
113
+ const data = await res.json();
114
+ if (typeof data.access_token !== "string" || typeof data.refresh_token !== "string") {
115
+ log.warn("Refresh response is missing token fields; treating as no credentials for this call");
116
+ return null;
117
+ }
118
+ return data;
119
+ }
120
+ /** O_EXCL 文件锁 + stale 清理。返回释放函数(幂等)。 */
121
+ async acquireLock() {
122
+ mkdirSync(dirname(this.lockPath), { recursive: true, mode: 448 });
123
+ const deadline = this.now() + this.lockStaleMs + 5e3;
124
+ for (; ; ) {
125
+ try {
126
+ const fd = openSync(this.lockPath, "wx");
127
+ writeSync(fd, `${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}`);
128
+ closeSync(fd);
129
+ let released = false;
130
+ return () => {
131
+ if (released) return;
132
+ released = true;
133
+ rmSync(this.lockPath, { force: true });
134
+ };
135
+ } catch {
136
+ try {
137
+ const age = this.now() - statSync(this.lockPath).mtimeMs;
138
+ if (age > this.lockStaleMs) {
139
+ rmSync(this.lockPath, { force: true });
140
+ continue;
141
+ }
142
+ } catch {
143
+ continue;
144
+ }
145
+ if (this.now() > deadline) {
146
+ throw new Error(
147
+ "Timed out waiting for the refresh lock (another lune-mcp process may be stuck; delete ~/.lune-mcp/refresh.lock and retry)"
148
+ );
149
+ }
150
+ await new Promise((r) => setTimeout(r, this.lockPollMs));
151
+ }
152
+ }
153
+ }
154
+ };
155
+
156
+ export {
157
+ KeychainCredentialProvider
158
+ };