@yoonion/mimi-seed-mcp 0.25.2 → 0.25.4

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.
Files changed (43) hide show
  1. package/README.md +6 -5
  2. package/assets/agent-guide.md +29 -5
  3. package/dist/auth/cli.js +2 -2
  4. package/dist/auth/constants.d.ts +5 -2
  5. package/dist/auth/constants.js +17 -10
  6. package/dist/auth/errors.js +8 -5
  7. package/dist/auth/google-auth.d.ts +27 -0
  8. package/dist/auth/google-auth.js +39 -3
  9. package/dist/core/console-url.d.ts +19 -0
  10. package/dist/core/console-url.js +61 -0
  11. package/dist/core/credential-store.js +2 -0
  12. package/dist/drive/tools.d.ts +0 -1
  13. package/dist/drive/tools.js +19 -1
  14. package/dist/i18n/tools-en/android.d.ts +2 -2
  15. package/dist/i18n/tools-en/android.js +2 -2
  16. package/dist/i18n/tools-en/jenkins.d.ts +4 -4
  17. package/dist/i18n/tools-en/jenkins.js +4 -4
  18. package/dist/instagram/browser-login.js +4 -3
  19. package/dist/jenkins/credentials.d.ts +7 -3
  20. package/dist/jenkins/credentials.js +4 -0
  21. package/dist/jenkins/messages.d.ts +2 -0
  22. package/dist/jenkins/messages.js +15 -0
  23. package/dist/lib/human-approval.d.ts +49 -0
  24. package/dist/lib/human-approval.js +143 -0
  25. package/dist/lib/package-root.d.ts +5 -0
  26. package/dist/lib/tool-registrar.d.ts +31 -0
  27. package/dist/lib/tool-registrar.js +80 -3
  28. package/dist/registers/android.js +10 -7
  29. package/dist/registers/auth.js +16 -7
  30. package/dist/registers/jenkins.js +20 -8
  31. package/dist/remote-sync.js +13 -4
  32. package/dist/server.js +2 -1
  33. package/dist/social/broker-base.d.ts +7 -0
  34. package/dist/social/broker-base.js +11 -0
  35. package/dist/social/meta-app-config.d.ts +19 -0
  36. package/dist/social/meta-app-config.js +83 -0
  37. package/dist/social/meta-direct-login.d.ts +45 -0
  38. package/dist/social/meta-direct-login.js +307 -0
  39. package/dist/social/setup-cli.js +231 -22
  40. package/dist/threads/browser-login.js +4 -3
  41. package/npm-shrinkwrap.json +1985 -0
  42. package/package.json +6 -3
  43. package/tool-manifest.json +26 -0
@@ -0,0 +1,307 @@
1
+ // Broker-free Instagram / Threads browser login with the user's own Meta app.
2
+ //
3
+ // The app secret never leaves this machine: the CLI opens the provider's authorize page, receives the
4
+ // authorization code (from a loopback callback, or from the redirected URL the user pastes back), exchanges it
5
+ // for a short-lived token, upgrades that to a long-lived (~60 day) token, then hands it to the same verified
6
+ // save path the MCP tools use (connectInstagram / connectThreads). Nothing is saved unless that verification
7
+ // succeeds, so a failed login keeps the existing connection.
8
+ //
9
+ // Two redirect modes, because Meta's rules for loopback redirects are inconsistent across products:
10
+ // - http://localhost:<port>/<path> (or 127.0.0.1 / [::1]) — a local server catches the callback;
11
+ // - any HTTPS URI (e.g. https://localhost/...) — the browser lands on a page that may not load, and the user
12
+ // pastes the full address-bar URL back into the terminal.
13
+ // Both modes verify `state` before using the code.
14
+ import { createServer } from 'node:http';
15
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
16
+ import { fetchWithTimeout } from '../lib/http.js';
17
+ import { openSystemBrowser } from '../auth/browser.js';
18
+ import { connectInstagram } from '../instagram/setup.js';
19
+ import { connectThreads } from '../threads/setup.js';
20
+ import { resolveSocialConfigTarget } from './profile-store.js';
21
+ import { isLoopbackRedirect, isValidRedirectUri } from './meta-app-config.js';
22
+ export class MetaDirectLoginError extends Error {
23
+ code;
24
+ detail;
25
+ constructor(code,
26
+ /** Provider's own reason (e.g. a redirect_uri mismatch), already scrubbed of the code and secret. */
27
+ detail) {
28
+ super(`Meta direct login: ${code}${detail ? ` (${detail})` : ''}`);
29
+ this.code = code;
30
+ this.detail = detail;
31
+ }
32
+ }
33
+ /** Scopes cover what the instagram_* / threads_* tools call: account lookup and publishing. */
34
+ export const META_LOGIN_PROVIDERS = {
35
+ instagram: {
36
+ authorizeUrl: 'https://www.instagram.com/oauth/authorize',
37
+ tokenUrl: 'https://api.instagram.com/oauth/access_token',
38
+ longLivedUrl: 'https://graph.instagram.com/access_token',
39
+ longLivedGrant: 'ig_exchange_token',
40
+ scopes: ['instagram_business_basic', 'instagram_business_content_publish'],
41
+ },
42
+ threads: {
43
+ authorizeUrl: 'https://threads.net/oauth/authorize',
44
+ tokenUrl: 'https://graph.threads.net/oauth/access_token',
45
+ longLivedUrl: 'https://graph.threads.net/access_token',
46
+ longLivedGrant: 'th_exchange_token',
47
+ scopes: ['threads_basic', 'threads_content_publish'],
48
+ },
49
+ };
50
+ const MAX_LIFETIME_SECONDS = 60 * 24 * 3600;
51
+ export function buildAuthorizeUrl(platform, app, state) {
52
+ const spec = META_LOGIN_PROVIDERS[platform];
53
+ const url = new URL(spec.authorizeUrl);
54
+ url.searchParams.set('client_id', app.appId);
55
+ url.searchParams.set('redirect_uri', app.redirectUri);
56
+ url.searchParams.set('scope', spec.scopes.join(','));
57
+ url.searchParams.set('response_type', 'code');
58
+ url.searchParams.set('state', state);
59
+ return url.href;
60
+ }
61
+ function sameState(actual, expected) {
62
+ return /^[a-f0-9]{64}$/.test(actual) && timingSafeEqual(Buffer.from(actual), Buffer.from(expected));
63
+ }
64
+ function validCode(code) {
65
+ return !!code && code.length <= 4096 && /^[A-Za-z0-9._~-]+$/.test(code);
66
+ }
67
+ /**
68
+ * Extract the authorization code from a pasted redirect URL. The URL must point at the registered redirect
69
+ * (same origin and path) and carry the expected state; a bare code is refused because it cannot be tied to
70
+ * this login attempt.
71
+ */
72
+ export function parsePastedRedirect(input, app, state) {
73
+ let url;
74
+ try {
75
+ url = new URL(input.trim());
76
+ }
77
+ catch {
78
+ throw new MetaDirectLoginError('state');
79
+ }
80
+ const expected = new URL(app.redirectUri);
81
+ if (url.origin !== expected.origin || url.pathname !== expected.pathname)
82
+ throw new MetaDirectLoginError('state');
83
+ // Meta's cancel redirect (?error=access_denied&error_reason=user_denied…) carries no state, so check it first —
84
+ // otherwise a cancelled consent is reported as "not this login's redirect". A denial can only abort the login.
85
+ if (url.searchParams.has('error'))
86
+ throw new MetaDirectLoginError('denied');
87
+ if (!sameState(url.searchParams.get('state') ?? '', state))
88
+ throw new MetaDirectLoginError('state');
89
+ // Instagram appends "#_" to the redirect; URL parsing already moves it into the fragment.
90
+ const code = url.searchParams.get('code');
91
+ if (!validCode(code))
92
+ throw new MetaDirectLoginError('exchange');
93
+ return code;
94
+ }
95
+ function scrub(text, secrets) {
96
+ let out = text;
97
+ for (const secret of secrets)
98
+ if (secret)
99
+ out = out.split(secret).join('***');
100
+ return out.slice(0, 300);
101
+ }
102
+ /** Provider error reason without echoing tokens: only the documented message fields are read. */
103
+ function providerReason(body, secrets) {
104
+ try {
105
+ const parsed = JSON.parse(body);
106
+ const nested = parsed.error && typeof parsed.error === 'object' ? parsed.error.message : undefined;
107
+ const message = typeof parsed.error_message === 'string' ? parsed.error_message
108
+ : typeof nested === 'string' ? nested : undefined;
109
+ return message ? scrub(message, secrets) : undefined;
110
+ }
111
+ catch {
112
+ // A non-JSON error body has no documented reason field; the caller still fails with code 'exchange'.
113
+ return undefined;
114
+ }
115
+ }
116
+ async function readJson(response, secrets) {
117
+ const text = await response.text();
118
+ if (!response.ok)
119
+ throw new MetaDirectLoginError('exchange', providerReason(text, secrets));
120
+ try {
121
+ const parsed = JSON.parse(text);
122
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
123
+ throw new Error('not an object');
124
+ return parsed;
125
+ }
126
+ catch {
127
+ throw new MetaDirectLoginError('exchange');
128
+ }
129
+ }
130
+ /** code → short-lived token → long-lived token. The code is single-use, so the POST is never retried. */
131
+ export async function exchangeCode(platform, app, code) {
132
+ const spec = META_LOGIN_PROVIDERS[platform];
133
+ const secrets = [app.appSecret, code];
134
+ let shortLived;
135
+ try {
136
+ const response = await fetchWithTimeout(spec.tokenUrl, {
137
+ method: 'POST',
138
+ redirect: 'error',
139
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
140
+ body: new URLSearchParams({
141
+ client_id: app.appId,
142
+ client_secret: app.appSecret,
143
+ grant_type: 'authorization_code',
144
+ redirect_uri: app.redirectUri,
145
+ code,
146
+ }).toString(),
147
+ }, { timeoutMs: 30_000, maxAttempts: 1 });
148
+ const body = await readJson(response, secrets);
149
+ // Instagram has returned both { access_token } and { data: [{ access_token }] }.
150
+ const record = Array.isArray(body.data) && body.data[0] && typeof body.data[0] === 'object'
151
+ ? body.data[0] : body;
152
+ if (typeof record.access_token !== 'string' || !record.access_token)
153
+ throw new MetaDirectLoginError('exchange');
154
+ shortLived = record.access_token;
155
+ }
156
+ catch (error) {
157
+ if (error instanceof MetaDirectLoginError)
158
+ throw error;
159
+ throw new MetaDirectLoginError('exchange'); // network errors may quote the request; do not echo them
160
+ }
161
+ try {
162
+ const url = new URL(spec.longLivedUrl);
163
+ url.searchParams.set('grant_type', spec.longLivedGrant);
164
+ url.searchParams.set('client_secret', app.appSecret);
165
+ url.searchParams.set('access_token', shortLived);
166
+ const body = await readJson(await fetchWithTimeout(url, { redirect: 'error' }, 30_000), [...secrets, shortLived]);
167
+ const expiresIn = body.expires_in;
168
+ if (typeof body.access_token !== 'string' || !body.access_token ||
169
+ typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0 || expiresIn > MAX_LIFETIME_SECONDS) {
170
+ throw new MetaDirectLoginError('exchange');
171
+ }
172
+ return { accessToken: body.access_token, expiresInSeconds: expiresIn };
173
+ }
174
+ catch (error) {
175
+ if (error instanceof MetaDirectLoginError)
176
+ throw error;
177
+ throw new MetaDirectLoginError('exchange');
178
+ }
179
+ }
180
+ function listen(server, port, host) {
181
+ return new Promise((resolve, reject) => {
182
+ server.once('error', reject);
183
+ server.listen(port, host, () => { server.off('error', reject); resolve(); });
184
+ });
185
+ }
186
+ /** Wait for the provider to redirect to the loopback URI and return the code. */
187
+ async function captureLoopback(app, state, timeoutMs, onReady) {
188
+ const redirect = new URL(app.redirectUri);
189
+ let settled = false;
190
+ let finish;
191
+ let fail;
192
+ const result = new Promise((resolve, reject) => { finish = resolve; fail = reject; });
193
+ void result.catch(() => { });
194
+ const handler = (req, res) => {
195
+ res.setHeader('Cache-Control', 'no-store');
196
+ res.setHeader('Referrer-Policy', 'no-referrer');
197
+ res.setHeader('Content-Security-Policy', "default-src 'none'");
198
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
199
+ if (req.method !== 'GET' || url.pathname !== redirect.pathname) {
200
+ res.writeHead(404).end();
201
+ return;
202
+ }
203
+ if (settled) {
204
+ res.writeHead(409).end('Login already handled.');
205
+ return;
206
+ }
207
+ // Meta's cancel redirect carries no state. Checking state first answered "Invalid login state." and left the CLI
208
+ // waiting out the full timeout. A forged denial (state absent or matching) can only end this local login early.
209
+ const returned = url.searchParams.get('state');
210
+ if (url.searchParams.has('error') && (returned === null || sameState(returned, state))) {
211
+ settled = true;
212
+ res.writeHead(400).end('Login cancelled. Return to Mimi Seed.');
213
+ fail(new MetaDirectLoginError('denied'));
214
+ return;
215
+ }
216
+ if (!sameState(returned ?? '', state)) {
217
+ res.writeHead(400).end('Invalid login state.');
218
+ return;
219
+ }
220
+ const code = url.searchParams.get('code');
221
+ if (!validCode(code)) {
222
+ res.writeHead(400).end('Invalid callback.');
223
+ return;
224
+ }
225
+ settled = true;
226
+ res.end('Approval received. Return to Mimi Seed to check the connection result.');
227
+ finish(code);
228
+ };
229
+ // "localhost" may resolve to either loopback family in the browser, so listen on both when asked for it.
230
+ const hosts = redirect.hostname === 'localhost' ? ['127.0.0.1', '::1']
231
+ : [redirect.hostname === '[::1]' ? '::1' : redirect.hostname];
232
+ const servers = [];
233
+ let timer;
234
+ try {
235
+ for (const host of hosts) {
236
+ const server = createServer(handler);
237
+ try {
238
+ await listen(server, Number(redirect.port), host);
239
+ servers.push(server);
240
+ }
241
+ catch (error) {
242
+ // Only "this machine has no IPv6 loopback" is safe to skip. A port that is *in use* on either family must
243
+ // fail: the browser may resolve localhost to that family and hand ?code&state to the other process, and
244
+ // this login would then wait for the full timeout.
245
+ const code = error.code;
246
+ if (host === '::1' && hosts.length > 1 && (code === 'EADDRNOTAVAIL' || code === 'EAFNOSUPPORT'))
247
+ continue;
248
+ throw new MetaDirectLoginError('configuration', `port ${redirect.port} is not available on ${host}`);
249
+ }
250
+ }
251
+ if (servers.length === 0)
252
+ throw new MetaDirectLoginError('configuration', `port ${redirect.port} is not available`);
253
+ timer = setTimeout(() => { settled = true; fail(new MetaDirectLoginError('timeout')); }, timeoutMs);
254
+ await onReady();
255
+ return await result;
256
+ }
257
+ finally {
258
+ if (timer)
259
+ clearTimeout(timer);
260
+ for (const server of servers) {
261
+ server.close();
262
+ server.closeAllConnections();
263
+ }
264
+ }
265
+ }
266
+ export async function connectWithMetaApp(platform, options) {
267
+ const { app } = options;
268
+ if (!isValidRedirectUri(app.redirectUri))
269
+ throw new MetaDirectLoginError('configuration');
270
+ // Freeze the selected profile before any asynchronous work / directory changes.
271
+ const target = resolveSocialConfigTarget(platform, options);
272
+ const saveOptions = { ...options, profile: target.profile ?? undefined, startDir: options.startDir ?? process.cwd() };
273
+ const timeoutMs = options.timeoutMs ?? 600_000;
274
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000)
275
+ throw new MetaDirectLoginError('configuration');
276
+ const state = randomBytes(32).toString('hex');
277
+ const authorizeUrl = buildAuthorizeUrl(platform, app, state);
278
+ const open = async () => {
279
+ options.onUrl?.(authorizeUrl);
280
+ try {
281
+ await (options.openBrowser ?? openSystemBrowser)(authorizeUrl);
282
+ }
283
+ catch {
284
+ if (!options.onUrl)
285
+ throw new MetaDirectLoginError('configuration', 'could not open a browser');
286
+ }
287
+ };
288
+ let code;
289
+ if (isLoopbackRedirect(app.redirectUri)) {
290
+ code = await captureLoopback(app, state, timeoutMs, open);
291
+ }
292
+ else {
293
+ if (!options.readRedirect)
294
+ throw new MetaDirectLoginError('configuration');
295
+ await open();
296
+ code = parsePastedRedirect(await options.readRedirect(), app, state);
297
+ }
298
+ const token = await exchangeCode(platform, app, code);
299
+ const connect = platform === 'instagram' ? connectInstagram : connectThreads;
300
+ // Resolve the canonical account ID from /me rather than the OAuth user_id (numeric ids can lose precision).
301
+ const connected = await connect(token.accessToken, undefined, true, saveOptions, token.expiresInSeconds);
302
+ // Keep the verifier's own reason (e.g. "not a professional account") — it is the same text the MCP tools show,
303
+ // and the only thing that tells the user what to fix. Scrubbed anyway: it must never echo the token or secret.
304
+ if (!connected.ok)
305
+ throw new MetaDirectLoginError('validation', scrub(connected.text, [token.accessToken, app.appSecret, code]));
306
+ return connected;
307
+ }