@firefunc-agent/runner 0.7.1 → 0.9.3
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/LICENSE +7 -3
- package/README.md +296 -4
- package/dist/activity.d.ts +32 -0
- package/dist/activity.js +295 -0
- package/dist/api.d.ts +69 -1
- package/dist/api.js +114 -3
- package/dist/brief.d.ts +11 -0
- package/dist/brief.js +278 -0
- package/dist/build-info.json +4 -0
- package/dist/cli.js +59 -2
- package/dist/config.d.ts +7 -0
- package/dist/config.js +3 -0
- package/dist/cut.d.ts +45 -0
- package/dist/cut.js +105 -0
- package/dist/daemon.d.ts +16 -0
- package/dist/daemon.js +196 -7
- package/dist/declined.d.ts +11 -0
- package/dist/declined.js +27 -0
- package/dist/engines/antigravity.d.ts +2 -0
- package/dist/engines/antigravity.js +102 -0
- package/dist/engines/claude-budget.d.ts +1 -1
- package/dist/engines/claude-budget.js +2 -72
- package/dist/engines/claude.js +139 -2
- package/dist/engines/codex.js +10 -3
- package/dist/engines/copilot.d.ts +2 -0
- package/dist/engines/copilot.js +117 -0
- package/dist/engines/cursor.js +4 -0
- package/dist/engines/gemini.js +6 -1
- package/dist/engines/index.d.ts +2 -0
- package/dist/engines/index.js +22 -4
- package/dist/engines/types.d.ts +12 -1
- package/dist/exec.d.ts +3 -0
- package/dist/exec.js +48 -5
- package/dist/firefunc/agents.d.ts +2 -0
- package/dist/firefunc/agents.js +343 -0
- package/dist/firefunc/args.d.ts +18 -0
- package/dist/firefunc/args.js +82 -0
- package/dist/firefunc/auth.d.ts +21 -0
- package/dist/firefunc/auth.js +129 -0
- package/dist/firefunc/catalog.d.ts +10 -0
- package/dist/firefunc/catalog.js +201 -0
- package/dist/firefunc/cli.d.ts +2 -0
- package/dist/firefunc/cli.js +24 -0
- package/dist/firefunc/client.d.ts +36 -0
- package/dist/firefunc/client.js +177 -0
- package/dist/firefunc/command.d.ts +28 -0
- package/dist/firefunc/command.js +35 -0
- package/dist/firefunc/config.d.ts +29 -0
- package/dist/firefunc/config.js +111 -0
- package/dist/firefunc/configure.d.ts +6 -0
- package/dist/firefunc/configure.js +409 -0
- package/dist/firefunc/io.d.ts +25 -0
- package/dist/firefunc/io.js +14 -0
- package/dist/firefunc/main.d.ts +4 -0
- package/dist/firefunc/main.js +259 -0
- package/dist/firefunc/output.d.ts +29 -0
- package/dist/firefunc/output.js +131 -0
- package/dist/firefunc/prompt.d.ts +14 -0
- package/dist/firefunc/prompt.js +58 -0
- package/dist/firefunc/skill.d.ts +3 -0
- package/dist/firefunc/skill.js +80 -0
- package/dist/firefunc/tasks.d.ts +2 -0
- package/dist/firefunc/tasks.js +279 -0
- package/dist/firefunc/version.d.ts +2 -0
- package/dist/firefunc/version.js +8 -0
- package/dist/git-auth.d.ts +4 -1
- package/dist/git-auth.js +6 -2
- package/dist/held.d.ts +18 -0
- package/dist/held.js +95 -0
- package/dist/job.d.ts +3 -0
- package/dist/job.js +818 -102
- package/dist/keep-local.d.ts +12 -0
- package/dist/keep-local.js +651 -0
- package/dist/limit.d.ts +30 -0
- package/dist/limit.js +258 -0
- package/dist/locks.d.ts +14 -0
- package/dist/locks.js +164 -0
- package/dist/machine-logins.d.ts +19 -0
- package/dist/machine-logins.js +187 -0
- package/dist/mcp-login.d.ts +24 -0
- package/dist/mcp-login.js +993 -0
- package/dist/mcp-proxy.d.ts +21 -0
- package/dist/mcp-proxy.js +180 -0
- package/dist/mcp.d.ts +62 -0
- package/dist/mcp.js +611 -0
- package/dist/network.d.ts +20 -0
- package/dist/network.js +76 -0
- package/dist/orphans.d.ts +40 -0
- package/dist/orphans.js +235 -0
- package/dist/pending.d.ts +14 -0
- package/dist/pending.js +56 -0
- package/dist/pool.d.ts +7 -0
- package/dist/pool.js +57 -9
- package/dist/pr-title.d.ts +11 -0
- package/dist/pr-title.js +63 -0
- package/dist/recover.d.ts +10 -0
- package/dist/recover.js +104 -0
- package/dist/secret-scan.d.ts +19 -0
- package/dist/secret-scan.js +161 -0
- package/dist/session-stream.d.ts +9 -1
- package/dist/session-stream.js +20 -2
- package/dist/skills.d.ts +11 -0
- package/dist/skills.js +164 -0
- package/dist/stopped.d.ts +3 -0
- package/dist/stopped.js +10 -0
- package/dist/usage.d.ts +49 -0
- package/dist/usage.js +389 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +17 -0
- package/dist/viewer.js +7 -1
- package/dist/worktrees.d.ts +15 -0
- package/dist/worktrees.js +96 -0
- package/package.json +8 -5
- package/skill/firefunc/SKILL.md +222 -0
|
@@ -0,0 +1,993 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
3
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, } from 'node:fs';
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { homedir, hostname } from 'node:os';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
import { configPath } from './config.js';
|
|
9
|
+
import { claudeCodeLogins } from './machine-logins.js';
|
|
10
|
+
function out(msg) {
|
|
11
|
+
process.stdout.write(`${msg}\n`);
|
|
12
|
+
}
|
|
13
|
+
function err(msg) {
|
|
14
|
+
process.stderr.write(`${msg}\n`);
|
|
15
|
+
}
|
|
16
|
+
const KNOWN_SERVERS = [
|
|
17
|
+
{
|
|
18
|
+
id: 'github',
|
|
19
|
+
label: 'GitHub remote MCP server',
|
|
20
|
+
url: 'https://api.githubcopilot.com/mcp/',
|
|
21
|
+
dispatched: true,
|
|
22
|
+
refusal: {
|
|
23
|
+
reason: 'GitHub is the one vendor FireFunc can mint a credential for. Each run gets a fresh ' +
|
|
24
|
+
'installation token, scoped to that run’s repository, read-only, valid one hour — which ' +
|
|
25
|
+
'is narrower than anything a machine-wide login could be.',
|
|
26
|
+
fix: 'Nothing to do: GitHub MCP needs no login on this machine. If a run reports no GitHub server, the cause is on the FireFunc side (GitHub not connected to the workspace, or the App missing a read permission), and the API log names which.',
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: 'jira',
|
|
31
|
+
label: 'Atlassian Rovo MCP Server',
|
|
32
|
+
url: 'https://mcp.atlassian.com/v2/mcp',
|
|
33
|
+
dispatched: false,
|
|
34
|
+
refusal: null,
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
id: 'linear',
|
|
38
|
+
label: 'Linear MCP server (read-only endpoint)',
|
|
39
|
+
url: 'https://mcp.linear.app/mcp/readonly',
|
|
40
|
+
dispatched: false,
|
|
41
|
+
refusal: {
|
|
42
|
+
reason: 'Linear publishes no tool names, so FireFunc has nothing to allowlist and never puts this ' +
|
|
43
|
+
'server in a run. A login here would authenticate a server your agents can call nothing on.',
|
|
44
|
+
fix: 'Nothing you can do on this machine — the missing piece is a recorded tools/list from Linear’s server, which is FireFunc-side work. Linear stays reachable through the ordinary connector in the meantime.',
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
id: 'sentry',
|
|
49
|
+
label: 'Sentry MCP server',
|
|
50
|
+
url: 'https://mcp.sentry.dev/mcp',
|
|
51
|
+
dispatched: false,
|
|
52
|
+
refusal: {
|
|
53
|
+
reason: 'Sentry publishes no maturity label for this server, so FireFunc has not switched it on and ' +
|
|
54
|
+
'never puts it in a run. A login here would be cached and unused.',
|
|
55
|
+
fix: 'Nothing you can do on this machine. Sentry issues and events still reach your agents through the ordinary connector and the run’s context pack.',
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: 'figma',
|
|
60
|
+
label: 'Figma MCP server (remote)',
|
|
61
|
+
url: 'https://mcp.figma.com/mcp',
|
|
62
|
+
dispatched: true,
|
|
63
|
+
refusal: {
|
|
64
|
+
reason: 'Figma admits only clients listed in its MCP Catalog — "Only clients listed in the Figma ' +
|
|
65
|
+
'MCP Catalog are able to connect to the Figma MCP Server" (developers.figma.com) — and ' +
|
|
66
|
+
'dynamic client registration answers 403 to everything else. The FireFunc runner is not ' +
|
|
67
|
+
'listed, so it does not connect to this server and this login has nothing to register.',
|
|
68
|
+
fix: 'Nothing is needed for READING a design: that goes through FireFunc on the organization\u2019s ' +
|
|
69
|
+
'own Figma connection (the REST API, a far larger limit), and your agents already have it.\n' +
|
|
70
|
+
'DRAWING is different — create_new_file, generate_figma_design and generate_diagram exist ' +
|
|
71
|
+
'only on Figma\u2019s own MCP server. If you want an agent on this machine to draw, sign ' +
|
|
72
|
+
'CLAUDE CODE in to Figma once here: `claude mcp add --transport http figma ' +
|
|
73
|
+
'https://mcp.figma.com/mcp`, then inside `claude` run `/mcp` and authenticate figma. Claude ' +
|
|
74
|
+
'Code is a catalog client and the connection is its own; FireFunc never sees the ' +
|
|
75
|
+
'credential.\n' +
|
|
76
|
+
'Know what that spends. Figma meters this server PER SEAT and a read costs the same as a ' +
|
|
77
|
+
'write: about 6 calls a month on a View or Collab seat, 200 a day on a Dev or Full seat. ' +
|
|
78
|
+
'Unattended runs on this machine will draw from the allowance of whoever signed in here.',
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
id: 'slack',
|
|
83
|
+
label: 'Slack MCP server',
|
|
84
|
+
url: 'https://mcp.slack.com/mcp',
|
|
85
|
+
dispatched: false,
|
|
86
|
+
refusal: {
|
|
87
|
+
reason: 'Slack publishes no machine-readable tool names, so FireFunc has nothing to allowlist and ' +
|
|
88
|
+
'never puts this server in a run. Its read tools also need user-token search scopes that ' +
|
|
89
|
+
'FireFunc’s workspace install does not hold.',
|
|
90
|
+
fix: 'Nothing you can do on this machine. Slack messages still reach your agents through the ordinary connector.',
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
];
|
|
94
|
+
function knownServer(tool) {
|
|
95
|
+
return KNOWN_SERVERS.find((s) => s.id === tool) ?? null;
|
|
96
|
+
}
|
|
97
|
+
export function mcpLoginDir() {
|
|
98
|
+
return join(dirname(configPath()), 'mcp-logins');
|
|
99
|
+
}
|
|
100
|
+
export function mcpLoginPath(server) {
|
|
101
|
+
return join(mcpLoginDir(), `${server}.json`);
|
|
102
|
+
}
|
|
103
|
+
function repoContaining(path) {
|
|
104
|
+
let current = dirname(path);
|
|
105
|
+
for (;;) {
|
|
106
|
+
if (existsSync(join(current, '.git')))
|
|
107
|
+
return current;
|
|
108
|
+
const parent = dirname(current);
|
|
109
|
+
if (parent === current)
|
|
110
|
+
return null;
|
|
111
|
+
current = parent;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function refuseIfInsideARepo(dir) {
|
|
115
|
+
const repo = repoContaining(dir);
|
|
116
|
+
if (!repo)
|
|
117
|
+
return false;
|
|
118
|
+
err(`Refusing to cache MCP logins inside a git repository.\n\n` +
|
|
119
|
+
` logins: ${dir}\n` +
|
|
120
|
+
` repo: ${repo}\n\n` +
|
|
121
|
+
`These files hold live vendor tokens. The runner stages its worktrees with\n` +
|
|
122
|
+
`"git add -A" and pushes them, so a credential under a checkout is one ignore-rule\n` +
|
|
123
|
+
`mistake away from being permanent in a pull request.\n\n` +
|
|
124
|
+
`Fix: the logins live beside the runner config, so unset FIREFUNC_RUNNER_CONFIG (the\n` +
|
|
125
|
+
`default is ${join(homedir(), '.firefunc-runner', 'config.json')}) or point it\n` +
|
|
126
|
+
`outside every repository on this machine, then run this again.`);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
function readLogin(server) {
|
|
130
|
+
const path = mcpLoginPath(server);
|
|
131
|
+
if (!existsSync(path))
|
|
132
|
+
return null;
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
135
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
136
|
+
return null;
|
|
137
|
+
const record = parsed;
|
|
138
|
+
return typeof record.accessToken === 'string' && record.accessToken ? record : null;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function writeLogin(record) {
|
|
145
|
+
const path = mcpLoginPath(record.server);
|
|
146
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
147
|
+
writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
|
|
148
|
+
try {
|
|
149
|
+
chmodSync(path, 0o600);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function heldLogins() {
|
|
155
|
+
let names = [];
|
|
156
|
+
try {
|
|
157
|
+
names = readdirSync(mcpLoginDir()).filter((n) => n.endsWith('.json'));
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return [];
|
|
161
|
+
}
|
|
162
|
+
return names
|
|
163
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
164
|
+
.sort()
|
|
165
|
+
.map((server) => ({ server, record: readLogin(server) }));
|
|
166
|
+
}
|
|
167
|
+
function wrap(text, width) {
|
|
168
|
+
const lines = [];
|
|
169
|
+
let current = '';
|
|
170
|
+
for (const word of text.split(' ')) {
|
|
171
|
+
if (current && current.length + 1 + word.length > width) {
|
|
172
|
+
lines.push(current);
|
|
173
|
+
current = word;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
current = current ? `${current} ${word}` : word;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (current)
|
|
180
|
+
lines.push(current);
|
|
181
|
+
return lines;
|
|
182
|
+
}
|
|
183
|
+
function humanDuration(ms) {
|
|
184
|
+
const mins = Math.round(ms / 60_000);
|
|
185
|
+
if (mins < 1)
|
|
186
|
+
return 'under a minute';
|
|
187
|
+
if (mins < 90)
|
|
188
|
+
return `${mins}m`;
|
|
189
|
+
const hours = Math.round(mins / 60);
|
|
190
|
+
if (hours < 48)
|
|
191
|
+
return `${hours}h`;
|
|
192
|
+
return `${Math.round(hours / 24)}d`;
|
|
193
|
+
}
|
|
194
|
+
function expiryOf(record, now) {
|
|
195
|
+
if (!record.expiresAt) {
|
|
196
|
+
return {
|
|
197
|
+
state: 'unknown',
|
|
198
|
+
text: 'expiry unknown — the server did not say when this token ends',
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
const at = Date.parse(record.expiresAt);
|
|
202
|
+
if (Number.isNaN(at)) {
|
|
203
|
+
return { state: 'unknown', text: 'expiry unreadable in the cache' };
|
|
204
|
+
}
|
|
205
|
+
const delta = at - now.getTime();
|
|
206
|
+
const stamp = new Date(at).toISOString().replace('T', ' ').slice(0, 16);
|
|
207
|
+
return delta > 0
|
|
208
|
+
? { state: 'valid', text: `expires ${stamp}Z (in ${humanDuration(delta)})` }
|
|
209
|
+
: { state: 'expired', text: `EXPIRED ${humanDuration(-delta)} ago (${stamp}Z)` };
|
|
210
|
+
}
|
|
211
|
+
function isSafeEndpoint(url) {
|
|
212
|
+
let parsed;
|
|
213
|
+
try {
|
|
214
|
+
parsed = new URL(url);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
if (parsed.protocol === 'https:')
|
|
220
|
+
return true;
|
|
221
|
+
return (parsed.protocol === 'http:' &&
|
|
222
|
+
(parsed.hostname === '127.0.0.1' ||
|
|
223
|
+
parsed.hostname === 'localhost' ||
|
|
224
|
+
parsed.hostname === '::1'));
|
|
225
|
+
}
|
|
226
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
227
|
+
async function getJson(url) {
|
|
228
|
+
if (!isSafeEndpoint(url))
|
|
229
|
+
return null;
|
|
230
|
+
try {
|
|
231
|
+
const res = await fetch(url, {
|
|
232
|
+
headers: { accept: 'application/json' },
|
|
233
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
234
|
+
});
|
|
235
|
+
if (!res.ok)
|
|
236
|
+
return null;
|
|
237
|
+
const body = await res.json();
|
|
238
|
+
return body && typeof body === 'object' && !Array.isArray(body)
|
|
239
|
+
? body
|
|
240
|
+
: null;
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function str(record, key) {
|
|
247
|
+
const value = record[key];
|
|
248
|
+
return typeof value === 'string' && value ? value : null;
|
|
249
|
+
}
|
|
250
|
+
function strArray(record, key) {
|
|
251
|
+
const value = record[key];
|
|
252
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === 'string' && !!v) : [];
|
|
253
|
+
}
|
|
254
|
+
const WRITE_SCOPE = /(^|[:._-])(write|delete|manage|admin|create|update|modify|edit|remove)([:._-]|$)/i;
|
|
255
|
+
function readOnlyScopes(scopes) {
|
|
256
|
+
return scopes.filter((s) => !WRITE_SCOPE.test(s));
|
|
257
|
+
}
|
|
258
|
+
async function protectedResourceMetadataUrls(serverUrl) {
|
|
259
|
+
const candidates = [];
|
|
260
|
+
try {
|
|
261
|
+
const res = await fetch(serverUrl, {
|
|
262
|
+
method: 'POST',
|
|
263
|
+
headers: {
|
|
264
|
+
'content-type': 'application/json',
|
|
265
|
+
accept: 'application/json, text/event-stream',
|
|
266
|
+
},
|
|
267
|
+
body: JSON.stringify({
|
|
268
|
+
jsonrpc: '2.0',
|
|
269
|
+
id: 1,
|
|
270
|
+
method: 'initialize',
|
|
271
|
+
params: {
|
|
272
|
+
protocolVersion: '2025-06-18',
|
|
273
|
+
capabilities: {},
|
|
274
|
+
clientInfo: { name: 'firefunc-runner', version: 'mcp-login' },
|
|
275
|
+
},
|
|
276
|
+
}),
|
|
277
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
278
|
+
});
|
|
279
|
+
const challenge = res.headers.get('www-authenticate') ?? '';
|
|
280
|
+
const advertised = /resource_metadata="([^"]+)"/i.exec(challenge)?.[1];
|
|
281
|
+
if (advertised)
|
|
282
|
+
candidates.push(advertised);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
const parsed = new URL(serverUrl);
|
|
288
|
+
const path = parsed.pathname.replace(/\/+$/, '');
|
|
289
|
+
if (path)
|
|
290
|
+
candidates.push(`${parsed.origin}/.well-known/oauth-protected-resource${path}`);
|
|
291
|
+
candidates.push(`${parsed.origin}/.well-known/oauth-protected-resource`);
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
}
|
|
295
|
+
return candidates;
|
|
296
|
+
}
|
|
297
|
+
function authServerMetadataUrls(issuer) {
|
|
298
|
+
const urls = [];
|
|
299
|
+
try {
|
|
300
|
+
const parsed = new URL(issuer);
|
|
301
|
+
const path = parsed.pathname.replace(/\/+$/, '');
|
|
302
|
+
if (path) {
|
|
303
|
+
urls.push(`${parsed.origin}/.well-known/oauth-authorization-server${path}`);
|
|
304
|
+
urls.push(`${parsed.origin}/.well-known/openid-configuration${path}`);
|
|
305
|
+
urls.push(`${parsed.origin}${path}/.well-known/oauth-authorization-server`);
|
|
306
|
+
urls.push(`${parsed.origin}${path}/.well-known/openid-configuration`);
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
urls.push(`${parsed.origin}/.well-known/oauth-authorization-server`);
|
|
310
|
+
urls.push(`${parsed.origin}/.well-known/openid-configuration`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
}
|
|
315
|
+
return urls;
|
|
316
|
+
}
|
|
317
|
+
async function discover(serverUrl) {
|
|
318
|
+
let resource = null;
|
|
319
|
+
let issuers = [];
|
|
320
|
+
let resourceScopes = [];
|
|
321
|
+
for (const url of await protectedResourceMetadataUrls(serverUrl)) {
|
|
322
|
+
const doc = await getJson(url);
|
|
323
|
+
if (!doc)
|
|
324
|
+
continue;
|
|
325
|
+
resource = str(doc, 'resource');
|
|
326
|
+
issuers = strArray(doc, 'authorization_servers');
|
|
327
|
+
resourceScopes = strArray(doc, 'scopes_supported');
|
|
328
|
+
if (issuers.length)
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
const candidates = issuers.length
|
|
332
|
+
? issuers
|
|
333
|
+
: (() => {
|
|
334
|
+
try {
|
|
335
|
+
return [new URL(serverUrl).origin];
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return [];
|
|
339
|
+
}
|
|
340
|
+
})();
|
|
341
|
+
for (const issuer of candidates) {
|
|
342
|
+
for (const url of authServerMetadataUrls(issuer)) {
|
|
343
|
+
const doc = await getJson(url);
|
|
344
|
+
if (!doc)
|
|
345
|
+
continue;
|
|
346
|
+
const tokenEndpoint = str(doc, 'token_endpoint');
|
|
347
|
+
if (!tokenEndpoint || !isSafeEndpoint(tokenEndpoint))
|
|
348
|
+
continue;
|
|
349
|
+
const methods = strArray(doc, 'code_challenge_methods_supported');
|
|
350
|
+
return {
|
|
351
|
+
issuer: str(doc, 'issuer') ?? issuer,
|
|
352
|
+
authorizationEndpoint: str(doc, 'authorization_endpoint'),
|
|
353
|
+
tokenEndpoint,
|
|
354
|
+
registrationEndpoint: str(doc, 'registration_endpoint'),
|
|
355
|
+
deviceEndpoint: str(doc, 'device_authorization_endpoint'),
|
|
356
|
+
revocationEndpoint: str(doc, 'revocation_endpoint'),
|
|
357
|
+
resource,
|
|
358
|
+
scope: readOnlyScopes(resourceScopes.length ? resourceScopes : strArray(doc, 'scopes_supported')).join(' '),
|
|
359
|
+
supportsS256: methods.length === 0 || methods.includes('S256'),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
refusal: `${serverUrl} did not advertise an OAuth authorization server.`,
|
|
365
|
+
fix: 'Check that this machine can reach the server (a proxy or an egress allowlist is the usual cause), then try again. If the vendor authenticates this server with something other than OAuth — an API token in a header, for example — this command cannot perform that login and the credential has to be configured wherever that vendor documents.',
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function browserOpener() {
|
|
369
|
+
if (process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.CI)
|
|
370
|
+
return null;
|
|
371
|
+
if (process.platform === 'darwin')
|
|
372
|
+
return { cmd: 'open', args: [] };
|
|
373
|
+
if (process.platform === 'win32')
|
|
374
|
+
return { cmd: 'cmd', args: ['/c', 'start', ''] };
|
|
375
|
+
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
|
|
376
|
+
return null;
|
|
377
|
+
return { cmd: 'xdg-open', args: [] };
|
|
378
|
+
}
|
|
379
|
+
function openBrowser(url, opener) {
|
|
380
|
+
try {
|
|
381
|
+
const child = spawn(opener.cmd, [...opener.args, url], { stdio: 'ignore', detached: true });
|
|
382
|
+
child.on('error', () => { });
|
|
383
|
+
child.unref();
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function base64url(buf) {
|
|
391
|
+
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
392
|
+
}
|
|
393
|
+
function pkce() {
|
|
394
|
+
const verifier = base64url(randomBytes(32));
|
|
395
|
+
return { verifier, challenge: base64url(createHash('sha256').update(verifier).digest()) };
|
|
396
|
+
}
|
|
397
|
+
async function postToken(endpoint, form, clientSecret) {
|
|
398
|
+
const body = new URLSearchParams(form);
|
|
399
|
+
const headers = {
|
|
400
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
401
|
+
accept: 'application/json',
|
|
402
|
+
};
|
|
403
|
+
if (clientSecret)
|
|
404
|
+
body.set('client_secret', clientSecret);
|
|
405
|
+
let res;
|
|
406
|
+
try {
|
|
407
|
+
res = await fetch(endpoint, {
|
|
408
|
+
method: 'POST',
|
|
409
|
+
headers,
|
|
410
|
+
body,
|
|
411
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
catch (e) {
|
|
415
|
+
return { error: 'unreachable', description: e.message };
|
|
416
|
+
}
|
|
417
|
+
let doc = null;
|
|
418
|
+
try {
|
|
419
|
+
const parsed = await res.json();
|
|
420
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
421
|
+
doc = parsed;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
catch {
|
|
425
|
+
}
|
|
426
|
+
if (!doc)
|
|
427
|
+
return { error: `http_${res.status}` };
|
|
428
|
+
const accessToken = str(doc, 'access_token');
|
|
429
|
+
if (!accessToken) {
|
|
430
|
+
return {
|
|
431
|
+
error: str(doc, 'error') ?? `http_${res.status}`,
|
|
432
|
+
description: str(doc, 'error_description') ?? undefined,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
const expiresIn = doc.expires_in;
|
|
436
|
+
return {
|
|
437
|
+
accessToken,
|
|
438
|
+
tokenType: str(doc, 'token_type') ?? 'Bearer',
|
|
439
|
+
refreshToken: str(doc, 'refresh_token') ?? undefined,
|
|
440
|
+
expiresAt: typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0
|
|
441
|
+
? new Date(Date.now() + expiresIn * 1000).toISOString()
|
|
442
|
+
: null,
|
|
443
|
+
scope: str(doc, 'scope') ?? undefined,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async function registerClient(meta, redirectUri, grantTypes) {
|
|
447
|
+
if (!meta.registrationEndpoint || !isSafeEndpoint(meta.registrationEndpoint)) {
|
|
448
|
+
return {
|
|
449
|
+
refusal: `${meta.issuer} does not offer dynamic client registration.`,
|
|
450
|
+
fix: 'This command can only sign in where the vendor lets a client register itself. A vendor that admits only its own listed clients has to be signed into from one of them — the engine CLI on this machine (Claude Code, Codex, Gemini CLI, Cursor) keeps its own session, outside FireFunc.',
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
let res;
|
|
454
|
+
try {
|
|
455
|
+
res = await fetch(meta.registrationEndpoint, {
|
|
456
|
+
method: 'POST',
|
|
457
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
458
|
+
body: JSON.stringify({
|
|
459
|
+
client_name: `FireFunc runner (${hostname()})`,
|
|
460
|
+
application_type: 'native',
|
|
461
|
+
grant_types: grantTypes,
|
|
462
|
+
response_types: grantTypes.includes('authorization_code') ? ['code'] : [],
|
|
463
|
+
token_endpoint_auth_method: 'none',
|
|
464
|
+
...(redirectUri ? { redirect_uris: [redirectUri] } : {}),
|
|
465
|
+
...(meta.scope ? { scope: meta.scope } : {}),
|
|
466
|
+
}),
|
|
467
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
catch (e) {
|
|
471
|
+
return {
|
|
472
|
+
refusal: `Could not reach ${meta.issuer} to register this machine (${e.message}).`,
|
|
473
|
+
fix: 'Check this machine’s network access to that host — a proxy or an egress allowlist is the usual cause — and run the command again.',
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const parsed = res.ok ? await res.json().catch(() => null) : null;
|
|
477
|
+
const doc = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
478
|
+
? parsed
|
|
479
|
+
: null;
|
|
480
|
+
const clientId = doc ? str(doc, 'client_id') : null;
|
|
481
|
+
if (!doc || !clientId) {
|
|
482
|
+
return {
|
|
483
|
+
refusal: `${meta.issuer} refused to register this machine as a client (HTTP ${res.status}).`,
|
|
484
|
+
fix: res.status === 403
|
|
485
|
+
? 'A 403 here means the vendor admits only clients it has approved. Sign in from the engine CLI on this machine instead — it keeps its own session with that vendor, outside FireFunc.'
|
|
486
|
+
: 'Read the vendor’s MCP documentation for whether client registration is enabled for your plan or tenant; an admin setting usually controls it.',
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
return { clientId, clientSecret: str(doc, 'client_secret') ?? undefined };
|
|
490
|
+
}
|
|
491
|
+
function waitForCode(server, state, acceptPaste, timeoutMs) {
|
|
492
|
+
return new Promise((resolve) => {
|
|
493
|
+
let settled = false;
|
|
494
|
+
const rl = acceptPaste
|
|
495
|
+
? createInterface({ input: process.stdin, output: process.stdout, terminal: false })
|
|
496
|
+
: null;
|
|
497
|
+
const finish = (result) => {
|
|
498
|
+
if (settled)
|
|
499
|
+
return;
|
|
500
|
+
settled = true;
|
|
501
|
+
clearTimeout(timer);
|
|
502
|
+
rl?.close();
|
|
503
|
+
server.close();
|
|
504
|
+
resolve(result);
|
|
505
|
+
};
|
|
506
|
+
const timer = setTimeout(() => finish({ failed: `no answer within ${Math.round(timeoutMs / 60_000)} minutes` }), timeoutMs);
|
|
507
|
+
server.on('request', (req, res) => {
|
|
508
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
509
|
+
const returned = url.searchParams;
|
|
510
|
+
const vendorError = returned.get('error');
|
|
511
|
+
const code = returned.get('code');
|
|
512
|
+
const body = vendorError
|
|
513
|
+
? `Sign-in was refused: ${vendorError}. You can close this tab.`
|
|
514
|
+
: code
|
|
515
|
+
? 'Signed in. You can close this tab and return to the terminal.'
|
|
516
|
+
: 'Waiting for the sign-in redirect.';
|
|
517
|
+
res.writeHead(vendorError ? 400 : 200, { 'content-type': 'text/plain; charset=utf-8' });
|
|
518
|
+
res.end(`FireFunc runner — ${body}\n`);
|
|
519
|
+
if (vendorError)
|
|
520
|
+
return finish({ failed: `the vendor refused the sign-in (${vendorError})` });
|
|
521
|
+
if (!code)
|
|
522
|
+
return;
|
|
523
|
+
if (returned.get('state') !== state) {
|
|
524
|
+
return finish({
|
|
525
|
+
failed: 'the redirect carried the wrong state value, so it was not the sign-in we started',
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
finish({ code });
|
|
529
|
+
});
|
|
530
|
+
rl?.on('line', (line) => {
|
|
531
|
+
const typed = line.trim();
|
|
532
|
+
if (!typed)
|
|
533
|
+
return;
|
|
534
|
+
let code = typed;
|
|
535
|
+
let returnedState = null;
|
|
536
|
+
if (/^https?:\/\//i.test(typed)) {
|
|
537
|
+
try {
|
|
538
|
+
const parsed = new URL(typed);
|
|
539
|
+
code = parsed.searchParams.get('code') ?? '';
|
|
540
|
+
returnedState = parsed.searchParams.get('state');
|
|
541
|
+
}
|
|
542
|
+
catch {
|
|
543
|
+
code = '';
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (!code) {
|
|
547
|
+
out('That did not contain a code. Paste the whole redirected URL, or the code itself.');
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (returnedState !== null && returnedState !== state) {
|
|
551
|
+
return finish({
|
|
552
|
+
failed: 'the pasted URL carried the wrong state value, so it was not this sign-in',
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
finish({ code });
|
|
556
|
+
});
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
async function deviceFlow(meta, clientId, clientSecret) {
|
|
560
|
+
if (!meta.deviceEndpoint)
|
|
561
|
+
return { failed: 'the authorization server offers no device flow' };
|
|
562
|
+
let doc = null;
|
|
563
|
+
try {
|
|
564
|
+
const res = await fetch(meta.deviceEndpoint, {
|
|
565
|
+
method: 'POST',
|
|
566
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
567
|
+
body: new URLSearchParams({
|
|
568
|
+
client_id: clientId,
|
|
569
|
+
...(meta.scope ? { scope: meta.scope } : {}),
|
|
570
|
+
...(meta.resource ? { resource: meta.resource } : {}),
|
|
571
|
+
}),
|
|
572
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
573
|
+
});
|
|
574
|
+
const parsed = await res.json();
|
|
575
|
+
if (parsed && typeof parsed === 'object')
|
|
576
|
+
doc = parsed;
|
|
577
|
+
}
|
|
578
|
+
catch (e) {
|
|
579
|
+
return { failed: `could not start the device flow (${e.message})` };
|
|
580
|
+
}
|
|
581
|
+
const deviceCode = doc ? str(doc, 'device_code') : null;
|
|
582
|
+
const userCode = doc ? str(doc, 'user_code') : null;
|
|
583
|
+
const verificationUri = doc ? str(doc, 'verification_uri') : null;
|
|
584
|
+
if (!doc || !deviceCode || !userCode || !verificationUri) {
|
|
585
|
+
return { failed: 'the device flow response was missing a code or a URL' };
|
|
586
|
+
}
|
|
587
|
+
const complete = str(doc, 'verification_uri_complete');
|
|
588
|
+
const expiresIn = typeof doc.expires_in === 'number' ? doc.expires_in : 900;
|
|
589
|
+
let intervalMs = (typeof doc.interval === 'number' ? doc.interval : 5) * 1000;
|
|
590
|
+
out('');
|
|
591
|
+
out('This machine has no browser to open, so finish the sign-in on another one:');
|
|
592
|
+
out('');
|
|
593
|
+
out(` 1. open ${verificationUri}`);
|
|
594
|
+
out(` 2. enter the code ${userCode}`);
|
|
595
|
+
if (complete)
|
|
596
|
+
out(` (or open ${complete}, which carries the code already)`);
|
|
597
|
+
out('');
|
|
598
|
+
out(`Waiting — this code is good for about ${Math.round(expiresIn / 60)} minutes.`);
|
|
599
|
+
const deadline = Date.now() + expiresIn * 1000;
|
|
600
|
+
for (;;) {
|
|
601
|
+
if (Date.now() > deadline)
|
|
602
|
+
return { failed: 'the device code expired before it was approved' };
|
|
603
|
+
await new Promise((r) => setTimeout(r, intervalMs));
|
|
604
|
+
const result = await postToken(meta.tokenEndpoint, {
|
|
605
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
606
|
+
device_code: deviceCode,
|
|
607
|
+
client_id: clientId,
|
|
608
|
+
...(meta.resource ? { resource: meta.resource } : {}),
|
|
609
|
+
}, clientSecret);
|
|
610
|
+
if ('accessToken' in result)
|
|
611
|
+
return result;
|
|
612
|
+
if (result.error === 'authorization_pending')
|
|
613
|
+
continue;
|
|
614
|
+
if (result.error === 'slow_down') {
|
|
615
|
+
intervalMs += 5_000;
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
failed: `${result.error}${result.description ? ` — ${result.description}` : ''}`,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function startLoopback() {
|
|
624
|
+
return new Promise((resolve) => {
|
|
625
|
+
const server = createServer();
|
|
626
|
+
server.on('error', () => resolve(null));
|
|
627
|
+
server.listen(0, '127.0.0.1', () => {
|
|
628
|
+
const address = server.address();
|
|
629
|
+
if (!address || typeof address === 'string') {
|
|
630
|
+
server.close();
|
|
631
|
+
return resolve(null);
|
|
632
|
+
}
|
|
633
|
+
resolve({ server, redirectUri: `http://127.0.0.1:${address.port}/callback` });
|
|
634
|
+
});
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
const CALLBACK_TIMEOUT_MS = 5 * 60_000;
|
|
638
|
+
function refuse(server) {
|
|
639
|
+
const refusal = server.refusal;
|
|
640
|
+
if (!refusal)
|
|
641
|
+
return;
|
|
642
|
+
err(`Not logging in to ${server.label}.\n\n${refusal.reason}\n\nFix: ${refusal.fix}`);
|
|
643
|
+
process.exitCode = 1;
|
|
644
|
+
}
|
|
645
|
+
function knownList() {
|
|
646
|
+
return KNOWN_SERVERS.map((s) => s.id).join(', ');
|
|
647
|
+
}
|
|
648
|
+
export async function runMcpLogin(tool, opts = {}) {
|
|
649
|
+
const server = knownServer(tool);
|
|
650
|
+
if (!server) {
|
|
651
|
+
err(`No MCP server is declared for "${tool}".\n\n` +
|
|
652
|
+
`Fix: use one of ${knownList()}. A tool absent from that list has no vendor MCP server ` +
|
|
653
|
+
`FireFunc knows about, so there is nothing on this machine to sign in to.`);
|
|
654
|
+
process.exitCode = 1;
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (server.refusal)
|
|
658
|
+
return refuse(server);
|
|
659
|
+
if (refuseIfInsideARepo(mcpLoginDir())) {
|
|
660
|
+
process.exitCode = 1;
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
const existing = readLogin(tool);
|
|
664
|
+
out(`Signing this machine in to ${server.label} (${server.url}).`);
|
|
665
|
+
const discovered = await discover(server.url);
|
|
666
|
+
if ('refusal' in discovered) {
|
|
667
|
+
err(`\n${discovered.refusal}\n\nFix: ${discovered.fix}`);
|
|
668
|
+
process.exitCode = 1;
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
const meta = discovered;
|
|
672
|
+
if (!meta.supportsS256) {
|
|
673
|
+
err(`\n${meta.issuer} does not offer PKCE with S256.\n\n` +
|
|
674
|
+
`Fix: none on this machine. Signing in without S256 would put an interceptable ` +
|
|
675
|
+
`authorization code on this machine’s loopback interface, and MCP requires S256 for ` +
|
|
676
|
+
`exactly that reason — this command will not fall back to a weaker exchange.`);
|
|
677
|
+
process.exitCode = 1;
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (existing?.refreshToken && existing.issuer === meta.issuer) {
|
|
681
|
+
const refreshed = await postToken(meta.tokenEndpoint, {
|
|
682
|
+
grant_type: 'refresh_token',
|
|
683
|
+
refresh_token: existing.refreshToken,
|
|
684
|
+
client_id: existing.clientId,
|
|
685
|
+
...(meta.resource ? { resource: meta.resource } : {}),
|
|
686
|
+
}, existing.clientSecret);
|
|
687
|
+
if ('accessToken' in refreshed) {
|
|
688
|
+
const renewed = {
|
|
689
|
+
...existing,
|
|
690
|
+
accessToken: refreshed.accessToken,
|
|
691
|
+
tokenType: refreshed.tokenType,
|
|
692
|
+
refreshToken: refreshed.refreshToken ?? existing.refreshToken,
|
|
693
|
+
expiresAt: refreshed.expiresAt,
|
|
694
|
+
scope: refreshed.scope ?? existing.scope,
|
|
695
|
+
obtainedAt: new Date().toISOString(),
|
|
696
|
+
};
|
|
697
|
+
writeLogin(renewed);
|
|
698
|
+
out('\nRenewed the existing login with its refresh token — no browser needed.');
|
|
699
|
+
printSuccess(server, renewed);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
out('The stored refresh token no longer works, so this needs a fresh sign-in.');
|
|
703
|
+
}
|
|
704
|
+
out('');
|
|
705
|
+
if (meta.scope) {
|
|
706
|
+
out('Asking for read-only access:');
|
|
707
|
+
for (const line of wrap(meta.scope, 72))
|
|
708
|
+
out(` ${line}`);
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
out(`${meta.issuer} publishes no read-only scope names, so this asks for that vendor's\n` +
|
|
712
|
+
`default grant — as wide as the account you sign in with. FireFunc allows read\n` +
|
|
713
|
+
`tools only, but the token itself will be whatever the vendor decides to issue.`);
|
|
714
|
+
}
|
|
715
|
+
const opener = opts.noBrowser ? null : browserOpener();
|
|
716
|
+
const canPaste = process.stdin.isTTY === true;
|
|
717
|
+
if (!opener && meta.deviceEndpoint) {
|
|
718
|
+
const registered = await registerClient(meta, null, [
|
|
719
|
+
'urn:ietf:params:oauth:grant-type:device_code',
|
|
720
|
+
'refresh_token',
|
|
721
|
+
]);
|
|
722
|
+
if ('refusal' in registered) {
|
|
723
|
+
err(`\n${registered.refusal}\n\nFix: ${registered.fix}`);
|
|
724
|
+
process.exitCode = 1;
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const result = await deviceFlow(meta, registered.clientId, registered.clientSecret);
|
|
728
|
+
if ('failed' in result) {
|
|
729
|
+
err(`\nSign-in did not complete: ${result.failed}.\n\nFix: run the command again.`);
|
|
730
|
+
process.exitCode = 1;
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const record = recordFrom(tool, server, meta, registered, result);
|
|
734
|
+
writeLogin(record);
|
|
735
|
+
printSuccess(server, record);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const loopback = await startLoopback();
|
|
739
|
+
if (!loopback) {
|
|
740
|
+
err(`\nCould not open a local listener on 127.0.0.1 to receive the sign-in redirect.\n\n` +
|
|
741
|
+
`Fix: something on this machine is blocking loopback listeners (a hardened sandbox or a ` +
|
|
742
|
+
`local firewall is the usual cause). Sign in on a machine where one can be opened; the ` +
|
|
743
|
+
`token is per machine either way.`);
|
|
744
|
+
process.exitCode = 1;
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
const registered = await registerClient(meta, loopback.redirectUri, [
|
|
748
|
+
'authorization_code',
|
|
749
|
+
'refresh_token',
|
|
750
|
+
]);
|
|
751
|
+
if ('refusal' in registered) {
|
|
752
|
+
loopback.server.close();
|
|
753
|
+
err(`\n${registered.refusal}\n\nFix: ${registered.fix}`);
|
|
754
|
+
process.exitCode = 1;
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
if (!meta.authorizationEndpoint || !isSafeEndpoint(meta.authorizationEndpoint)) {
|
|
758
|
+
loopback.server.close();
|
|
759
|
+
err(`\n${meta.issuer} published no https authorization endpoint, so there is no sign-in page to open.\n\n` +
|
|
760
|
+
`Fix: none on this machine — the vendor's own metadata is incomplete. Report it to them, ` +
|
|
761
|
+
`and use the ordinary connector for this tool in the meantime.`);
|
|
762
|
+
process.exitCode = 1;
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
const state = base64url(randomBytes(16));
|
|
766
|
+
const challenge = pkce();
|
|
767
|
+
const authorizeUrl = new URL(meta.authorizationEndpoint);
|
|
768
|
+
authorizeUrl.searchParams.set('response_type', 'code');
|
|
769
|
+
authorizeUrl.searchParams.set('client_id', registered.clientId);
|
|
770
|
+
authorizeUrl.searchParams.set('redirect_uri', loopback.redirectUri);
|
|
771
|
+
authorizeUrl.searchParams.set('state', state);
|
|
772
|
+
authorizeUrl.searchParams.set('code_challenge', challenge.challenge);
|
|
773
|
+
authorizeUrl.searchParams.set('code_challenge_method', 'S256');
|
|
774
|
+
if (meta.scope)
|
|
775
|
+
authorizeUrl.searchParams.set('scope', meta.scope);
|
|
776
|
+
if (meta.resource)
|
|
777
|
+
authorizeUrl.searchParams.set('resource', meta.resource);
|
|
778
|
+
const opened = opener ? openBrowser(authorizeUrl.href, opener) : false;
|
|
779
|
+
out('');
|
|
780
|
+
if (opened) {
|
|
781
|
+
out('Opened your browser to finish the sign-in. If it did not appear, open this:');
|
|
782
|
+
out(` ${authorizeUrl.href}`);
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
out(opts.noBrowser
|
|
786
|
+
? 'Not opening a browser (--no-browser). Open this URL wherever you can:'
|
|
787
|
+
: 'No browser can be opened on this machine, so open this URL wherever you can:');
|
|
788
|
+
out(` ${authorizeUrl.href}`);
|
|
789
|
+
out('');
|
|
790
|
+
if (canPaste) {
|
|
791
|
+
out(`After approving, your browser lands on ${loopback.redirectUri}?code=… — which will not\n` +
|
|
792
|
+
`load if you are on another machine. That is expected: copy the whole URL out of the\n` +
|
|
793
|
+
`address bar and paste it here, then press Return.`);
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
out(`This terminal is not interactive, so nothing can be pasted back. The sign-in only\n` +
|
|
797
|
+
`completes if the browser you use can reach ${loopback.redirectUri} —\n` +
|
|
798
|
+
`i.e. a browser on this machine, or an SSH tunnel to that port.`);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
out('');
|
|
802
|
+
out(`Waiting up to ${Math.round(CALLBACK_TIMEOUT_MS / 60_000)} minutes…`);
|
|
803
|
+
const code = await waitForCode(loopback.server, state, canPaste && !opened, CALLBACK_TIMEOUT_MS);
|
|
804
|
+
if ('failed' in code) {
|
|
805
|
+
err(`\nSign-in did not complete: ${code.failed}.\n\nFix: run the command again.`);
|
|
806
|
+
process.exitCode = 1;
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
const token = await postToken(meta.tokenEndpoint, {
|
|
810
|
+
grant_type: 'authorization_code',
|
|
811
|
+
code: code.code,
|
|
812
|
+
redirect_uri: loopback.redirectUri,
|
|
813
|
+
client_id: registered.clientId,
|
|
814
|
+
code_verifier: challenge.verifier,
|
|
815
|
+
...(meta.resource ? { resource: meta.resource } : {}),
|
|
816
|
+
}, registered.clientSecret);
|
|
817
|
+
if (!('accessToken' in token)) {
|
|
818
|
+
err(`\nThe sign-in was approved but ${meta.issuer} refused to issue a token ` +
|
|
819
|
+
`(${token.error}${token.description ? `: ${token.description}` : ''}).\n\n` +
|
|
820
|
+
`Fix: run the command again — an authorization code is single-use and expires in about a ` +
|
|
821
|
+
`minute, so a slow approval is the common cause. If it repeats, the vendor's error above ` +
|
|
822
|
+
`names the reason.`);
|
|
823
|
+
process.exitCode = 1;
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const record = recordFrom(tool, server, meta, registered, token);
|
|
827
|
+
writeLogin(record);
|
|
828
|
+
printSuccess(server, record);
|
|
829
|
+
}
|
|
830
|
+
function recordFrom(tool, server, meta, client, token) {
|
|
831
|
+
return {
|
|
832
|
+
server: tool,
|
|
833
|
+
tokenType: token.tokenType,
|
|
834
|
+
accessToken: token.accessToken,
|
|
835
|
+
expiresAt: token.expiresAt,
|
|
836
|
+
accountLabel: null,
|
|
837
|
+
serverUrl: server.url,
|
|
838
|
+
issuer: meta.issuer,
|
|
839
|
+
tokenEndpoint: meta.tokenEndpoint,
|
|
840
|
+
revocationEndpoint: meta.revocationEndpoint ?? undefined,
|
|
841
|
+
resource: meta.resource ?? undefined,
|
|
842
|
+
clientId: client.clientId,
|
|
843
|
+
clientSecret: client.clientSecret,
|
|
844
|
+
scope: token.scope ?? meta.scope ?? undefined,
|
|
845
|
+
refreshToken: token.refreshToken,
|
|
846
|
+
obtainedAt: new Date().toISOString(),
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
function printSuccess(server, record) {
|
|
850
|
+
const expiry = expiryOf(record, new Date());
|
|
851
|
+
out('');
|
|
852
|
+
out(`Signed in to ${server.label}.`);
|
|
853
|
+
out('');
|
|
854
|
+
out(` stored ${mcpLoginPath(record.server)}`);
|
|
855
|
+
out(` ${process.platform === 'win32'
|
|
856
|
+
? 'in your user profile, where only you and an administrator can read it'
|
|
857
|
+
: 'mode 0600 — readable only by you'}`);
|
|
858
|
+
out(` ${expiry.state === 'unknown' ? 'expiry ' : 'expires'} ${expiry.text}`);
|
|
859
|
+
if (record.refreshToken) {
|
|
860
|
+
out(' renewal a refresh token was stored, so running this again renews it without a browser');
|
|
861
|
+
}
|
|
862
|
+
out('');
|
|
863
|
+
out('The token stays on this machine. It is never sent to FireFunc, and FireFunc');
|
|
864
|
+
out('cannot read it — doing the sign-in here rather than server-side is the whole');
|
|
865
|
+
out('point: your vendor credential never touches our infrastructure.');
|
|
866
|
+
out('');
|
|
867
|
+
out('What this does NOT cover:');
|
|
868
|
+
out(' • THIS MACHINE ONLY. Every other runner needs its own');
|
|
869
|
+
out(` "firefunc-runner mcp login ${record.server}" — there is no shared login to copy,`);
|
|
870
|
+
out(' and copying this file to another machine is not supported.');
|
|
871
|
+
out(` • It does not switch ${record.server} on by itself. A run reaches that server only`);
|
|
872
|
+
out(` when FireFunc's per-run config includes ${record.server} for the agent that ran.`);
|
|
873
|
+
out(" Each run's local log names the servers the engine actually got — trust that");
|
|
874
|
+
out(' line, not this one.');
|
|
875
|
+
out(` • It grants exactly what this ${server.label} account can reach. Each run is`);
|
|
876
|
+
out(' additionally bounded to the tools FireFunc allowlists for it — reads, plus');
|
|
877
|
+
out(' any write tools cleared for that vendor and granted to that agent — but the');
|
|
878
|
+
out(" account's own reach is the outer ceiling and this login sets it. Sign in with");
|
|
879
|
+
out(' an account scoped the way you want your agents scoped.');
|
|
880
|
+
}
|
|
881
|
+
export function runMcpList() {
|
|
882
|
+
const now = new Date();
|
|
883
|
+
const held = heldLogins();
|
|
884
|
+
const pad = ' '.repeat(8);
|
|
885
|
+
out(`MCP logins on this machine — ${mcpLoginDir()}`);
|
|
886
|
+
out('');
|
|
887
|
+
if (!held.length) {
|
|
888
|
+
out(' (none)');
|
|
889
|
+
out('');
|
|
890
|
+
}
|
|
891
|
+
for (const { server: id, record } of held) {
|
|
892
|
+
const known = knownServer(id);
|
|
893
|
+
out(` ${id.padEnd(8)} ${known?.label ?? '(a custom server — FireFunc names it in the agent)'}`);
|
|
894
|
+
if (!record) {
|
|
895
|
+
out(` ${pad} UNREADABLE — ${mcpLoginPath(id)} is not a login this build can parse.`);
|
|
896
|
+
out(` ${pad} Fix: firefunc-runner mcp logout ${id}, then log in again.`);
|
|
897
|
+
out('');
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
const expiry = expiryOf(record, now);
|
|
901
|
+
out(` ${pad} ${record.serverUrl}`);
|
|
902
|
+
out(` ${pad} signed in ${record.obtainedAt.replace('T', ' ').slice(0, 16)}Z, ${expiry.text}`);
|
|
903
|
+
if (known && !known.dispatched) {
|
|
904
|
+
out(` ${pad} NOT USED BY RUNS — FireFunc does not configure this server for any agent.`);
|
|
905
|
+
}
|
|
906
|
+
if (expiry.state === 'expired') {
|
|
907
|
+
if (known?.refusal) {
|
|
908
|
+
out(` ${pad} Nothing to renew: "mcp login ${id}" says why.`);
|
|
909
|
+
}
|
|
910
|
+
else {
|
|
911
|
+
out(` ${pad} Fix: firefunc-runner mcp login ${id}`);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
out('');
|
|
915
|
+
}
|
|
916
|
+
const theirs = claudeCodeLogins(now.getTime());
|
|
917
|
+
out(`Claude Code's own MCP sign-ins on this machine (used by Claude runs):`);
|
|
918
|
+
out('');
|
|
919
|
+
if (!theirs.length) {
|
|
920
|
+
out(' (none for a tool FireFunc dispatches)');
|
|
921
|
+
}
|
|
922
|
+
for (const l of theirs) {
|
|
923
|
+
const known = knownServer(l.server);
|
|
924
|
+
out(` ${l.server.padEnd(8)} ${known?.label ?? l.serverUrl ?? ''}`);
|
|
925
|
+
if (l.state === 'error') {
|
|
926
|
+
out(` ${pad} NOT USABLE — ${l.detail ?? 'unreadable'}`);
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
out(` ${pad} ${l.state === 'expired' ? 'EXPIRED' : 'signed in'}` +
|
|
930
|
+
(l.expiresAt
|
|
931
|
+
? `, expires ${l.expiresAt.replace('T', ' ').slice(0, 16)}Z`
|
|
932
|
+
: ', expiry unknown'));
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
out('');
|
|
936
|
+
const loginable = KNOWN_SERVERS.filter((s) => !s.refusal).map((s) => s.id);
|
|
937
|
+
out(`Can be logged in on this machine: ${loginable.length ? loginable.join(', ') : '(none today)'}`);
|
|
938
|
+
out(`Run "firefunc-runner mcp login <tool>" for any of ${knownList()} to see the detail —`);
|
|
939
|
+
out('a tool that cannot be logged in says why, and what to do instead.');
|
|
940
|
+
out('');
|
|
941
|
+
out('These tokens are held only here and are never sent to FireFunc. Another machine');
|
|
942
|
+
out('running a runner needs its own sign-in.');
|
|
943
|
+
}
|
|
944
|
+
export async function runMcpLogout(tool) {
|
|
945
|
+
const path = mcpLoginPath(tool);
|
|
946
|
+
if (!existsSync(path)) {
|
|
947
|
+
out(`Not logged in to ${tool} on this machine — nothing to forget.`);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
const record = readLogin(tool);
|
|
951
|
+
rmSync(path, { force: true });
|
|
952
|
+
if (!record) {
|
|
953
|
+
out(`Removed ${path} — it held no login this build could read.`);
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
let revoked = false;
|
|
957
|
+
if (record.revocationEndpoint && isSafeEndpoint(record.revocationEndpoint)) {
|
|
958
|
+
try {
|
|
959
|
+
const body = new URLSearchParams({
|
|
960
|
+
token: record.refreshToken ?? record.accessToken,
|
|
961
|
+
token_type_hint: record.refreshToken ? 'refresh_token' : 'access_token',
|
|
962
|
+
client_id: record.clientId,
|
|
963
|
+
});
|
|
964
|
+
if (record.clientSecret)
|
|
965
|
+
body.set('client_secret', record.clientSecret);
|
|
966
|
+
const res = await fetch(record.revocationEndpoint, {
|
|
967
|
+
method: 'POST',
|
|
968
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
969
|
+
body,
|
|
970
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
971
|
+
});
|
|
972
|
+
revoked = res.ok;
|
|
973
|
+
}
|
|
974
|
+
catch {
|
|
975
|
+
revoked = false;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
const expiry = expiryOf(record, new Date());
|
|
979
|
+
out(`Forgot the ${tool} login on this machine.`);
|
|
980
|
+
if (revoked) {
|
|
981
|
+
out('It was also revoked at the vendor, so the token is dead everywhere.');
|
|
982
|
+
}
|
|
983
|
+
else if (expiry.state === 'expired') {
|
|
984
|
+
out('It had already expired, so there was nothing left to revoke at the vendor.');
|
|
985
|
+
}
|
|
986
|
+
else {
|
|
987
|
+
out('It was NOT revoked at the vendor — the token stays valid there' +
|
|
988
|
+
(expiry.state === 'valid' ? ` until it ${expiry.text}.` : '.') +
|
|
989
|
+
`\nFix: if it must be dead now, remove "FireFunc runner (${hostname()})" from the` +
|
|
990
|
+
'\nconnected apps list in that vendor’s account settings.');
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
//# sourceMappingURL=mcp-login.js.map
|