@yoonion/mimi-seed-mcp 0.25.3 → 0.25.5

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 (63) hide show
  1. package/README.md +2 -1
  2. package/assets/agent-guide.md +37 -9
  3. package/dist/auth/cli.js +2 -2
  4. package/dist/auth/constants.js +4 -3
  5. package/dist/auth/errors.js +4 -1
  6. package/dist/auth/google-auth.d.ts +14 -0
  7. package/dist/auth/google-auth.js +19 -1
  8. package/dist/core/console-url.d.ts +17 -2
  9. package/dist/core/console-url.js +54 -16
  10. package/dist/core/credential-store.js +2 -0
  11. package/dist/crosspost/ledger.d.ts +52 -0
  12. package/dist/crosspost/ledger.js +269 -0
  13. package/dist/crosspost/tools.d.ts +136 -0
  14. package/dist/crosspost/tools.js +821 -0
  15. package/dist/drive/tools.d.ts +0 -1
  16. package/dist/drive/tools.js +19 -1
  17. package/dist/facebook/api.d.ts +3 -2
  18. package/dist/facebook/api.js +6 -2
  19. package/dist/i18n/manifest-en.js +3 -0
  20. package/dist/i18n/tools-en/android.d.ts +2 -2
  21. package/dist/i18n/tools-en/android.js +2 -2
  22. package/dist/i18n/tools-en/crosspost.d.ts +23 -0
  23. package/dist/i18n/tools-en/crosspost.js +22 -0
  24. package/dist/i18n/tools-en/index.js +2 -0
  25. package/dist/i18n/tools-en/jenkins.d.ts +4 -4
  26. package/dist/i18n/tools-en/jenkins.js +4 -4
  27. package/dist/instagram/api.d.ts +3 -2
  28. package/dist/instagram/api.js +6 -2
  29. package/dist/instagram/browser-login.js +2 -5
  30. package/dist/jenkins/credentials.d.ts +7 -3
  31. package/dist/jenkins/credentials.js +4 -0
  32. package/dist/jenkins/messages.d.ts +2 -0
  33. package/dist/jenkins/messages.js +15 -0
  34. package/dist/lib/human-approval.d.ts +1 -1
  35. package/dist/lib/human-approval.js +4 -3
  36. package/dist/lib/meta-auth.d.ts +9 -0
  37. package/dist/lib/meta-auth.js +12 -3
  38. package/dist/lib/tool-menu.js +2 -1
  39. package/dist/lib/tool-registrar.js +13 -5
  40. package/dist/registers/android.js +10 -7
  41. package/dist/registers/auth.js +11 -5
  42. package/dist/registers/crosspost.d.ts +2 -0
  43. package/dist/registers/crosspost.js +81 -0
  44. package/dist/registers/jenkins.js +20 -8
  45. package/dist/remote-sync.js +8 -4
  46. package/dist/server.js +2 -0
  47. package/dist/social/broker-base.d.ts +7 -0
  48. package/dist/social/broker-base.js +11 -0
  49. package/dist/social/meta-app-config.d.ts +19 -0
  50. package/dist/social/meta-app-config.js +83 -0
  51. package/dist/social/meta-direct-login.d.ts +45 -0
  52. package/dist/social/meta-direct-login.js +307 -0
  53. package/dist/social/setup-cli.js +228 -20
  54. package/dist/threads/api.d.ts +4 -3
  55. package/dist/threads/api.js +9 -7
  56. package/dist/threads/browser-login.js +2 -5
  57. package/dist/tiktok-business/posting.d.ts +11 -1
  58. package/dist/tiktok-business/posting.js +18 -1
  59. package/dist/video/youtube-publish.d.ts +41 -1
  60. package/dist/video/youtube-publish.js +16 -1
  61. package/npm-shrinkwrap.json +2 -2
  62. package/package.json +1 -1
  63. package/tool-manifest.json +28 -8
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { consoleUrl } from '#core/console-url.js';
2
+ import { socialBrokerBase } from './broker-base.js';
3
3
  // mimi-seed-social-auth — Facebook 페이지 / Instagram 계정 연결.
4
4
  //
5
5
  // 검증·저장 구현은 facebook/setup.ts · instagram/setup.ts 에 있고, MCP 도구
@@ -27,6 +27,8 @@ import { connectThreads, refreshThreadsToken } from '../threads/setup.js';
27
27
  import { connectThreadsInBrowser, ThreadsLoginError } from '../threads/browser-login.js';
28
28
  import { resolveLang } from '#core/lang.js';
29
29
  import { resolveSocialConfigTarget } from './profile-store.js';
30
+ import { isValidAppId, isValidAppSecret, isValidRedirectUri, isLoopbackRedirect, loadMetaApp, saveMetaApp, } from './meta-app-config.js';
31
+ import { connectWithMetaApp, MetaDirectLoginError } from './meta-direct-login.js';
30
32
  // ko 가 원본이고 en 은 `typeof ko` 를 만족해야 한다 — 키를 빠뜨리면 컴파일이 깨진다.
31
33
  const ko = {
32
34
  title: ' 🤖 Mimi Seed — 소셜 계정 연결 (Facebook / Instagram / Threads)',
@@ -72,7 +74,45 @@ const ko = {
72
74
  thRefreshing: ' 🔄 기존 Threads 토큰 갱신 중...',
73
75
  thRefreshFallback: ' 자동 갱신에 실패했습니다. 다시 연결합니다.',
74
76
  profile: (id) => ` 소셜 프로필: ${id}`,
75
- invalidArgs: ' 사용법: mimi-seed-social-auth [facebook|instagram|threads|all] [--profile <id>] [--manual-token]',
77
+ invalidArgs: ' 사용법: mimi-seed-social-auth [facebook|instagram|threads|all] [--profile <id>] [--manual-token] [--reset-app]',
78
+ appHeader: (label) => ` 🔑 내 Meta 앱으로 ${label} 브라우저 로그인 (서버 없음 — 앱 시크릿은 이 컴퓨터에만 저장)`,
79
+ appSaved: (label, id) => ` 저장된 ${label} 앱 사용: ${id} (바꾸려면 --reset-app)`,
80
+ igAppSteps: [
81
+ ' 1. developers.facebook.com → 앱 → 사용 사례 "Instagram에서 메시지 및 콘텐츠 관리"',
82
+ ' → "Instagram 로그인을 통한 API 설정"',
83
+ ' 2. "Instagram 비즈니스 로그인 설정" → OAuth 리디렉션 URI 에 아래 리디렉션 주소를 그대로 등록',
84
+ ' 3. 같은 화면의 **Instagram 앱 ID / 앱 시크릿** (Meta 앱 ID 와 다름)',
85
+ ' 4. 앱이 개발 모드면: 앱 역할 → Instagram 테스터에 내 계정 추가 → Instagram 앱에서 초대 수락',
86
+ ],
87
+ thAppSteps: [
88
+ ' 1. developers.facebook.com → 앱 → 사용 사례 "Threads API 액세스" (threads_basic, threads_content_publish)',
89
+ ' 2. 사용 사례 설정 → 리디렉션 콜백 URL 에 아래 리디렉션 주소를 그대로 등록',
90
+ ' (제거·삭제 콜백 URL 도 채워야 저장됩니다)',
91
+ ' 3. 같은 화면의 **Threads 앱 ID / 앱 시크릿**',
92
+ ' 4. 앱이 개발 모드면: 앱 역할 → Threads 테스터에 내 계정 추가 → threads.net 설정 → 웹사이트 권한에서 초대 수락',
93
+ ],
94
+ redirectSuggest: (uri) => ` 리디렉션 주소 (권장): ${uri}\n (대시보드가 끝에 / 를 붙여 저장하면 그 모양 그대로 입력해야 합니다 — Meta 는 한 글자라도 다르면 거부합니다.)`,
95
+ askAppId: (label) => ` ${label} 앱 ID (엔터: 토큰 직접 입력으로 전환): `,
96
+ askAppSecret: (label) => ` ${label} 앱 시크릿: `,
97
+ askRedirect: (def) => ` 등록한 리디렉션 URI (엔터: ${def}): `,
98
+ badAppId: ' ❌ 앱 ID 는 숫자여야 합니다. 저장하지 않았습니다.',
99
+ badAppSecret: ' ❌ 앱 시크릿 형식이 아닙니다 (영문·숫자 16자 이상). 저장하지 않았습니다.',
100
+ badRedirect: ' ❌ 리디렉션 URI 는 https:// 이거나 포트가 있는 http://localhost 여야 하고, ?·# 를 포함할 수 없습니다.',
101
+ loopbackWait: ' 브라우저에서 로그인·권한 동의를 마치면 자동으로 연결됩니다. 이 터미널을 열어두세요.',
102
+ pasteHow: ' 권한 동의 후 브라우저가 "연결할 수 없음" 같은 페이지로 이동해도 정상입니다.',
103
+ pastePrompt: ' 그 페이지의 주소창 전체 URL 을 붙여 넣으세요: ',
104
+ directFailed: (code) => ` ❌ ${({
105
+ denied: '권한 동의가 취소되었습니다.',
106
+ timeout: '로그인 대기 시간이 지났습니다. 명령을 다시 실행해주세요.',
107
+ state: '붙여 넣은 URL 이 이번 로그인의 리디렉션 주소가 아닙니다 (state·경로 불일치). 다시 실행해주세요.',
108
+ exchange: '인증 코드를 토큰으로 바꾸지 못했습니다. 앱 ID·시크릿·리디렉션 URI 가 앱 대시보드와 정확히 같은지 확인하세요.',
109
+ validation: '받은 토큰으로 계정을 확인하지 못했습니다.',
110
+ configuration: '로그인을 시작하지 못했습니다.',
111
+ }[code] ?? code)} 기존 연결은 보존했습니다.`,
112
+ directReason: (detail) => ` Meta 응답: ${detail}`,
113
+ appLoadFailed: (message) => ` ⚠️ 저장된 앱 설정을 읽지 못했습니다 — 토큰 직접 입력으로 진행합니다.\n ${message}`,
114
+ appSaveFailed: (message) => ` ⚠️ 계정은 연결됐지만 앱 설정은 저장하지 못했습니다. 다음 로그인 때 앱 정보를 다시 묻습니다.\n ${message}`,
115
+ tokenAtAppId: ' 토큰처럼 보입니다 — 토큰 직접 입력으로 전환합니다. (앱 ID 칸에서는 엔터만 누르면 됩니다.)',
76
116
  };
77
117
  const en = {
78
118
  title: ' 🤖 Mimi Seed — Connect social accounts (Facebook / Instagram / Threads)',
@@ -116,13 +156,81 @@ const en = {
116
156
  thAskUserId: ' Threads user ID (optional, Enter to look it up): ',
117
157
  thExistingAction: ' [Enter/y] refresh current token [r] reconnect [n] skip: ',
118
158
  thRefreshing: ' 🔄 Refreshing the existing Threads token...',
119
- thRefreshFallback: ' Automatic refresh failed. Reconnecting in your browser.',
159
+ thRefreshFallback: ' Automatic refresh failed. Reconnecting.',
120
160
  profile: (id) => ` Social profile: ${id}`,
121
- invalidArgs: ' Usage: mimi-seed-social-auth [facebook|instagram|threads|all] [--profile <id>] [--manual-token]',
161
+ invalidArgs: ' Usage: mimi-seed-social-auth [facebook|instagram|threads|all] [--profile <id>] [--manual-token] [--reset-app]',
162
+ appHeader: (label) => ` 🔑 ${label} browser login with your own Meta app (no server — the app secret stays on this computer)`,
163
+ appSaved: (label, id) => ` Using the saved ${label} app: ${id} (change it with --reset-app)`,
164
+ igAppSteps: [
165
+ ' 1. developers.facebook.com → your app → use case "Manage messaging & content on Instagram"',
166
+ ' → "API setup with Instagram login"',
167
+ ' 2. "Set up Instagram business login" → add the redirect URI below, exactly, to OAuth redirect URIs',
168
+ ' 3. The **Instagram app ID / app secret** on that screen (not the Meta app ID)',
169
+ ' 4. If the app is in development mode: App roles → add your account as an Instagram Tester → accept in the Instagram app',
170
+ ],
171
+ thAppSteps: [
172
+ ' 1. developers.facebook.com → your app → use case "Access the Threads API" (threads_basic, threads_content_publish)',
173
+ ' 2. Use case settings → add the redirect URI below, exactly, to Redirect Callback URLs',
174
+ ' (the Uninstall and Delete callback URLs must be filled in too, or saving fails)',
175
+ ' 3. The **Threads app ID / app secret** on that screen',
176
+ ' 4. If the app is in development mode: App roles → add your account as a Threads Tester → accept under threads.net Settings → Website permissions',
177
+ ],
178
+ redirectSuggest: (uri) => ` Redirect URI (suggested): ${uri}\n (If the dashboard saves it with a trailing /, enter it exactly that way — Meta rejects any difference.)`,
179
+ askAppId: (label) => ` ${label} app ID (Enter: paste a token instead): `,
180
+ askAppSecret: (label) => ` ${label} app secret: `,
181
+ askRedirect: (def) => ` Registered redirect URI (Enter: ${def}): `,
182
+ badAppId: ' ❌ The app ID must be numeric. Nothing was saved.',
183
+ badAppSecret: ' ❌ That is not an app secret (16+ letters and digits). Nothing was saved.',
184
+ badRedirect: ' ❌ The redirect URI must be https:// or http://localhost with a port, without ? or #.',
185
+ loopbackWait: ' Finish login and consent in the browser; the connection completes automatically. Keep this terminal open.',
186
+ pasteHow: ' After consent the browser may show a "site can\'t be reached" page. That is expected.',
187
+ pastePrompt: ' Paste the full URL from that page\'s address bar: ',
188
+ directFailed: (code) => ` ❌ ${({
189
+ denied: 'Consent was cancelled.',
190
+ timeout: 'The login timed out. Run the command again.',
191
+ state: 'The pasted URL is not this login\'s redirect (state or path mismatch). Run the command again.',
192
+ exchange: 'Could not exchange the authorization code. Check that the app ID, secret, and redirect URI match the app dashboard exactly.',
193
+ validation: 'Could not verify the account with the returned token.',
194
+ configuration: 'Could not start the login.',
195
+ }[code] ?? code)} Existing credentials were preserved.`,
196
+ directReason: (detail) => ` Meta said: ${detail}`,
197
+ appLoadFailed: (message) => ` ⚠️ Could not read the saved app settings — continuing with token paste.\n ${message}`,
198
+ appSaveFailed: (message) => ` ⚠️ The account is connected, but the app settings were not saved. You will be asked for the app again next time.\n ${message}`,
199
+ tokenAtAppId: ' That looks like a token — switching to token paste. (At the app ID prompt, just press Enter.)',
122
200
  };
123
201
  const M = resolveLang() === 'en' ? en : ko;
124
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
202
+ // historySize 0: 입력 기록이 남으면 숨겨 입력한 앱 시크릿이 다음 프롬프트에서 ↑ 키로 그대로 되살아난다.
203
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, historySize: 0 });
204
+ // readline 이 stdin 을 raw 모드로 잡고 있어 Ctrl-C 가 프로세스에 가지 않는다. 리스너가 없으면 rl 만 닫혀
205
+ // 로그인 대기(로컬 콜백 서버)가 시간 초과까지 살아 있고, 프롬프트에서의 취소가 exit 0 (성공)으로 끝났다.
206
+ rl.on('SIGINT', () => {
207
+ console.log(`\n${M.cancelled}`);
208
+ rl.close();
209
+ process.exit(130);
210
+ });
125
211
  const ask = (q) => new Promise((r) => rl.question(q, (a) => r(a.trim())));
212
+ /**
213
+ * 입력을 화면에 찍지 않는 질문 — 앱 시크릿은 만료되지 않고 그 앱을 쓰는 모든 계정의 토큰을 만들 수 있어 터미널
214
+ * 스크롤백·화면 공유에 남으면 안 된다. readline 에는 공개 API 가 없어 출력 함수를 질문 동안만 바꾼다.
215
+ * TTY 가 아니면 찍을 화면도 없으니 그대로 읽는다.
216
+ */
217
+ const askHidden = (q) => {
218
+ if (!process.stdin.isTTY)
219
+ return ask(q);
220
+ const out = rl;
221
+ const original = out._writeToOutput;
222
+ return new Promise((r) => {
223
+ rl.question(q, (a) => {
224
+ out._writeToOutput = original;
225
+ process.stdout.write('\n');
226
+ r(a.trim());
227
+ });
228
+ // 프롬프트는 이미 찍혔다. 이후 입력 에코만 막는다.
229
+ out._writeToOutput = () => { };
230
+ });
231
+ };
232
+ /** 앱 ID 칸에 붙여 넣은 토큰 (IGAA… / EAA… / TH… 또는 긴 영숫자) — 예전 사용법 그대로 토큰 입력으로 보낸다. */
233
+ const looksLikeToken = (value) => /^(IGAA|EAA|TH)[A-Za-z0-9]/.test(value) || /^[A-Za-z0-9_-]{40,}$/.test(value);
126
234
  async function confirmReconnect(label, detail) {
127
235
  console.log(M.already(label, detail));
128
236
  const answer = await ask(M.reconnect);
@@ -172,7 +280,95 @@ async function setupFacebook(profile) {
172
280
  console.log(M.notSaved);
173
281
  return result.ok;
174
282
  }
175
- async function setupInstagram(profile, manualToken = false) {
283
+ /** Suggested redirect: HTTPS (Meta's dashboards accept it) on a port nothing listens on — the user pastes the URL back. */
284
+ const DEFAULT_REDIRECT_URI = 'https://localhost:8765/callback';
285
+ /**
286
+ * Broker-free browser login with the user's own Meta app.
287
+ * Returns null when the user declines (blank app ID) so the caller can fall back to token paste.
288
+ */
289
+ async function loginWithOwnApp(platform, options, resetApp) {
290
+ const label = platform === 'instagram' ? 'Instagram' : 'Threads';
291
+ // 파이프로 들어온 입력은 예전처럼 토큰이다 (`printf 'IGAA…' | mimi-seed auth instagram`) — 앱 단계를 건너뛴다.
292
+ if (!process.stdin.isTTY)
293
+ return null;
294
+ console.log(M.appHeader(label));
295
+ let app = null;
296
+ if (!resetApp) {
297
+ try {
298
+ app = loadMetaApp(platform);
299
+ }
300
+ catch (error) {
301
+ // 손상된 meta-apps.json 때문에 명령 전체가 죽지 않게 — 토큰 입력으로 계속한다 (파일은 건드리지 않는다).
302
+ console.error(M.appLoadFailed(error instanceof Error ? error.message : String(error)));
303
+ return null;
304
+ }
305
+ }
306
+ const isNew = !app;
307
+ if (app) {
308
+ console.log(M.appSaved(label, app.appId));
309
+ }
310
+ else {
311
+ for (const line of platform === 'instagram' ? M.igAppSteps : M.thAppSteps)
312
+ console.log(line);
313
+ console.log(M.redirectSuggest(DEFAULT_REDIRECT_URI));
314
+ console.log('');
315
+ const appId = await ask(M.askAppId(label));
316
+ if (!appId)
317
+ return null;
318
+ if (looksLikeToken(appId)) {
319
+ console.log(M.tokenAtAppId);
320
+ return null;
321
+ }
322
+ if (!isValidAppId(appId)) {
323
+ console.error(M.badAppId);
324
+ return false;
325
+ }
326
+ const appSecret = await askHidden(M.askAppSecret(label));
327
+ if (!isValidAppSecret(appSecret)) {
328
+ console.error(M.badAppSecret);
329
+ return false;
330
+ }
331
+ const redirectUri = (await ask(M.askRedirect(DEFAULT_REDIRECT_URI))) || DEFAULT_REDIRECT_URI;
332
+ if (!isValidRedirectUri(redirectUri)) {
333
+ console.error(M.badRedirect);
334
+ return false;
335
+ }
336
+ app = { appId, appSecret, redirectUri };
337
+ }
338
+ const loopback = isLoopbackRedirect(app.redirectUri);
339
+ console.log(loopback ? M.loopbackWait : M.pasteHow);
340
+ try {
341
+ const result = await connectWithMetaApp(platform, {
342
+ ...options,
343
+ app,
344
+ onUrl: (url) => { console.log(M.thUrl); console.log(url); },
345
+ readRedirect: loopback ? undefined : () => ask(M.pastePrompt),
346
+ });
347
+ console.log(indent(result.text));
348
+ // Save the app only once it has produced a verified login, so a typo is never persisted. The account is
349
+ // already saved at this point, so a failed app save is reported, not turned into a failed login.
350
+ if (isNew) {
351
+ try {
352
+ saveMetaApp(platform, app);
353
+ }
354
+ catch (error) {
355
+ console.error(M.appSaveFailed(error instanceof Error ? error.message : String(error)));
356
+ }
357
+ }
358
+ return true;
359
+ }
360
+ catch (error) {
361
+ if (error instanceof MetaDirectLoginError) {
362
+ console.error(M.directFailed(error.code));
363
+ // validation 의 detail 은 연결 검증 결과 원문(MCP 도구와 같은 문구)이라 'Meta 응답' 접두 없이 그대로 보인다.
364
+ if (error.detail)
365
+ console.error(error.code === 'validation' ? indent(error.detail) : M.directReason(error.detail));
366
+ return false;
367
+ }
368
+ throw error;
369
+ }
370
+ }
371
+ async function setupInstagram(profile, manualToken = false, resetApp = false) {
176
372
  console.log('');
177
373
  console.log(M.igHeader);
178
374
  const options = { profile };
@@ -183,7 +379,7 @@ async function setupInstagram(profile, manualToken = false) {
183
379
  if (existing && !(await confirmReconnect('Instagram', existing.username ?? existing.userId))) {
184
380
  return true;
185
381
  }
186
- if (!manualToken && consoleUrl(process.env.MIMI_SEED_WEB_BASE)) {
382
+ if (!manualToken && socialBrokerBase()) {
187
383
  console.log(M.igBrowser);
188
384
  try {
189
385
  const result = await connectInstagramInBrowser({ ...options, onUrl: (url) => { console.log(M.thUrl); console.log(url); console.log(M.thResume); } });
@@ -198,6 +394,11 @@ async function setupInstagram(profile, manualToken = false) {
198
394
  return false;
199
395
  }
200
396
  }
397
+ if (!manualToken) {
398
+ const direct = await loginWithOwnApp('instagram', options, resetApp);
399
+ if (direct !== null)
400
+ return direct;
401
+ }
201
402
  console.log(M.igHowTo);
202
403
  console.log(M.igIgaa);
203
404
  console.log(M.igEaa);
@@ -217,7 +418,7 @@ async function setupInstagram(profile, manualToken = false) {
217
418
  console.log(M.notSaved);
218
419
  return result.ok;
219
420
  }
220
- async function setupThreads(profile, manualToken = false) {
421
+ async function setupThreads(profile, manualToken = false, resetApp = false) {
221
422
  console.log('');
222
423
  console.log(M.thHeader);
223
424
  const options = { profile };
@@ -240,7 +441,7 @@ async function setupThreads(profile, manualToken = false) {
240
441
  console.log(M.thRefreshFallback);
241
442
  }
242
443
  }
243
- if (!manualToken && consoleUrl(process.env.MIMI_SEED_WEB_BASE)) {
444
+ if (!manualToken && socialBrokerBase()) {
244
445
  console.log(M.thBrowser);
245
446
  try {
246
447
  const result = await connectThreadsInBrowser({ ...options, onUrl: (url) => { console.log(M.thUrl); console.log(url); console.log(M.thResume); } });
@@ -255,6 +456,11 @@ async function setupThreads(profile, manualToken = false) {
255
456
  return false;
256
457
  }
257
458
  }
459
+ if (!manualToken) {
460
+ const direct = await loginWithOwnApp('threads', options, resetApp);
461
+ if (direct !== null)
462
+ return direct;
463
+ }
258
464
  console.log(M.thHowTo);
259
465
  console.log(M.thStep1);
260
466
  console.log(M.thStep2);
@@ -284,14 +490,16 @@ function indent(text) {
284
490
  async function main() {
285
491
  const args = process.argv.slice(2);
286
492
  const manualToken = args.includes('--manual-token');
493
+ const resetApp = args.includes('--reset-app');
494
+ const FLAGS = new Set(['--profile', '--manual-token', '--reset-app']);
287
495
  const profileIndex = args.indexOf('--profile');
288
496
  const profile = profileIndex >= 0 ? args[profileIndex + 1] : undefined;
289
497
  if (profileIndex >= 0 && !profile) {
290
498
  console.error(M.invalidArgs);
291
499
  process.exit(1);
292
500
  }
293
- const positional = args.filter((arg, index) => arg !== '--manual-token' && arg !== '--profile' && (profileIndex < 0 || index !== profileIndex + 1));
294
- if (positional.length > 1 || args.some((arg) => arg.startsWith('--') && arg !== '--profile' && arg !== '--manual-token')) {
501
+ const positional = args.filter((arg, index) => !FLAGS.has(arg) && (profileIndex < 0 || index !== profileIndex + 1));
502
+ if (positional.length > 1 || args.some((arg) => arg.startsWith('--') && !FLAGS.has(arg))) {
295
503
  console.error(M.invalidArgs);
296
504
  process.exit(1);
297
505
  }
@@ -303,15 +511,15 @@ async function main() {
303
511
  ok = await setupFacebook(profile);
304
512
  }
305
513
  else if (target === 'instagram' || target === 'ig') {
306
- ok = await setupInstagram(profile, manualToken);
514
+ ok = await setupInstagram(profile, manualToken, resetApp);
307
515
  }
308
516
  else if (target === 'threads' || target === 'th') {
309
- ok = await setupThreads(profile, manualToken);
517
+ ok = await setupThreads(profile, manualToken, resetApp);
310
518
  }
311
519
  else if (target === 'all' || target === 'meta') {
312
520
  const fb = await setupFacebook(profile);
313
- const ig = await setupInstagram(profile, manualToken);
314
- const th = await setupThreads(profile, manualToken);
521
+ const ig = await setupInstagram(profile, manualToken, resetApp);
522
+ const th = await setupThreads(profile, manualToken, resetApp);
315
523
  ok = fb && ig && th;
316
524
  }
317
525
  else {
@@ -320,19 +528,19 @@ async function main() {
320
528
  if (c === 'f')
321
529
  ok = await setupFacebook(profile);
322
530
  else if (c === 'i')
323
- ok = await setupInstagram(profile, manualToken);
531
+ ok = await setupInstagram(profile, manualToken, resetApp);
324
532
  else if (c === 't')
325
- ok = await setupThreads(profile, manualToken);
533
+ ok = await setupThreads(profile, manualToken, resetApp);
326
534
  else if (c === 'b') {
327
535
  // 기존 b=Facebook+Instagram 동작을 유지한다.
328
536
  const fb = await setupFacebook(profile);
329
- const ig = await setupInstagram(profile, manualToken);
537
+ const ig = await setupInstagram(profile, manualToken, resetApp);
330
538
  ok = fb && ig;
331
539
  }
332
540
  else if (c === 'a') {
333
541
  const fb = await setupFacebook(profile);
334
- const ig = await setupInstagram(profile, manualToken);
335
- const th = await setupThreads(profile, manualToken);
542
+ const ig = await setupInstagram(profile, manualToken, resetApp);
543
+ const th = await setupThreads(profile, manualToken, resetApp);
336
544
  ok = fb && ig && th;
337
545
  }
338
546
  else {