@wezzard/mcp-x-articles 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +12 -7
- package/README.md +12 -10
- package/dist/server.mjs +979 -600
- package/mcp_config.json +14 -8
- package/package.json +1 -1
- package/pi-mcp.json +1 -1
- package/plugin.json +1 -1
- package/skills/x-articles/SKILL.md +4 -2
package/dist/server.mjs
CHANGED
|
@@ -7261,32 +7261,82 @@ import { fileURLToPath } from "node:url";
|
|
|
7261
7261
|
// src/keychain.ts
|
|
7262
7262
|
import { execFileSync } from "node:child_process";
|
|
7263
7263
|
import { createHash } from "node:crypto";
|
|
7264
|
-
import {
|
|
7264
|
+
import {
|
|
7265
|
+
closeSync,
|
|
7266
|
+
existsSync,
|
|
7267
|
+
mkdirSync,
|
|
7268
|
+
openSync,
|
|
7269
|
+
readFileSync,
|
|
7270
|
+
renameSync,
|
|
7271
|
+
rmSync,
|
|
7272
|
+
statSync,
|
|
7273
|
+
writeFileSync
|
|
7274
|
+
} from "node:fs";
|
|
7265
7275
|
import { homedir } from "node:os";
|
|
7266
7276
|
import { join } from "node:path";
|
|
7267
7277
|
var DEFAULT_KEYCHAIN_SERVICE = "@wezzard/mcp-x-articles";
|
|
7268
|
-
var
|
|
7278
|
+
var CLIENT_ACCOUNT = "oauth2_client_credentials";
|
|
7279
|
+
var REFRESH_LOCK_STALE_MS = 3e4;
|
|
7280
|
+
var REFRESH_LOCK_TIMEOUT_MS = 15e3;
|
|
7281
|
+
var REFRESH_LOCK_POLL_MS = 50;
|
|
7269
7282
|
function keychainServiceName() {
|
|
7270
7283
|
return (process.env.MCP_X_ARTICLES_KEYCHAIN_SERVICE ?? "").trim() || DEFAULT_KEYCHAIN_SERVICE;
|
|
7271
7284
|
}
|
|
7285
|
+
function detectHostConfigUi() {
|
|
7286
|
+
const pluginRoot = (process.env.PLUGIN_ROOT ?? "").trim();
|
|
7287
|
+
const pluginData = (process.env.PLUGIN_DATA ?? "").trim();
|
|
7288
|
+
const isAntigravity = process.env.ANTIGRAVITY_VSCODE_HOST === "1" || Boolean((process.env.ANTIGRAVITY_AUTH_SUCCESS_APP ?? "").trim()) || Boolean(pluginRoot) || Boolean(pluginData);
|
|
7289
|
+
if (isAntigravity) {
|
|
7290
|
+
const baseSource = pluginRoot || pluginData;
|
|
7291
|
+
const segments = baseSource.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
7292
|
+
const dir = segments[segments.length - 1] || "x-articles";
|
|
7293
|
+
const configUiUrl = `customization://${dir}`;
|
|
7294
|
+
return {
|
|
7295
|
+
hasNativeConfigUi: true,
|
|
7296
|
+
hostName: "antigravity",
|
|
7297
|
+
configUiUrl,
|
|
7298
|
+
setupInstruction: `Open Antigravity's MCP plugin configuration UI at [X Articles](${configUiUrl}) and configure X_OAUTH2_CLIENT_ID and X_OAUTH2_CLIENT_SECRET (and optionally X_OAUTH2_REFRESH_TOKEN from https://console.x.com -> Keys & Tokens -> OAuth 2.0 Keys -> Access Token -> Generate).`
|
|
7299
|
+
};
|
|
7300
|
+
}
|
|
7301
|
+
if ((process.env.CURSOR_PLUGIN_ROOT ?? "").trim()) {
|
|
7302
|
+
return {
|
|
7303
|
+
hasNativeConfigUi: true,
|
|
7304
|
+
hostName: "cursor",
|
|
7305
|
+
configUiUrl: null,
|
|
7306
|
+
setupInstruction: "Open Cursor's MCP plugin settings UI and configure X_OAUTH2_CLIENT_ID and X_OAUTH2_CLIENT_SECRET (and optionally X_OAUTH2_REFRESH_TOKEN from https://console.x.com -> Keys & Tokens -> OAuth 2.0 Keys -> Access Token -> Generate)."
|
|
7307
|
+
};
|
|
7308
|
+
}
|
|
7309
|
+
return {
|
|
7310
|
+
hasNativeConfigUi: false,
|
|
7311
|
+
hostName: "none",
|
|
7312
|
+
configUiUrl: null,
|
|
7313
|
+
setupInstruction: "Call `x_article_auth_status({ login: true })` to open the local browser setup form (saves OAuth 2.0 Client ID/Secret directly to macOS Keychain and completes X OAuth 2.0 PKCE with offline.access), or run `npx @wezzard/mcp-x-articles auth` in a terminal."
|
|
7314
|
+
};
|
|
7315
|
+
}
|
|
7272
7316
|
function cleanEnvValue(raw) {
|
|
7273
7317
|
const val = (raw ?? "").trim();
|
|
7274
7318
|
if (!val || val.startsWith("${")) return "";
|
|
7275
7319
|
return val;
|
|
7276
7320
|
}
|
|
7321
|
+
function sha256Hex(value) {
|
|
7322
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
7323
|
+
}
|
|
7324
|
+
function clientKeyId(clientId) {
|
|
7325
|
+
return sha256Hex(clientId).slice(0, 16);
|
|
7326
|
+
}
|
|
7277
7327
|
function configDirPath() {
|
|
7278
7328
|
const xdg = (process.env.XDG_CONFIG_HOME ?? "").trim();
|
|
7279
7329
|
const base = xdg ? xdg : join(homedir(), ".config");
|
|
7280
7330
|
return join(base, "mcp-x-articles");
|
|
7281
7331
|
}
|
|
7282
|
-
function
|
|
7283
|
-
return join(configDirPath(), "
|
|
7332
|
+
function clientCredentialsFilePath() {
|
|
7333
|
+
return join(configDirPath(), "oauth2_client.json");
|
|
7284
7334
|
}
|
|
7285
7335
|
function tokensFilePath() {
|
|
7286
|
-
return join(configDirPath(), "
|
|
7336
|
+
return join(configDirPath(), "oauth2_tokens.json");
|
|
7287
7337
|
}
|
|
7288
|
-
function
|
|
7289
|
-
return
|
|
7338
|
+
function refreshLockFilePath() {
|
|
7339
|
+
return join(configDirPath(), "oauth2_refresh.lock");
|
|
7290
7340
|
}
|
|
7291
7341
|
function isMacKeychainAvailable() {
|
|
7292
7342
|
if (process.platform !== "darwin") return false;
|
|
@@ -7331,13 +7381,6 @@ function keychainDelete(account) {
|
|
|
7331
7381
|
} catch {
|
|
7332
7382
|
}
|
|
7333
7383
|
}
|
|
7334
|
-
function clearConsumerCredentials() {
|
|
7335
|
-
keychainDelete(CONSUMER_ACCOUNT);
|
|
7336
|
-
const file = credentialsFilePath();
|
|
7337
|
-
if (existsSync(file)) {
|
|
7338
|
-
writeAtomic0600(file, {});
|
|
7339
|
-
}
|
|
7340
|
-
}
|
|
7341
7384
|
function writeAtomic0600(filePath, data) {
|
|
7342
7385
|
const dir = configDirPath();
|
|
7343
7386
|
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
@@ -7358,27 +7401,37 @@ function readJsonSafe(filePath) {
|
|
|
7358
7401
|
return null;
|
|
7359
7402
|
}
|
|
7360
7403
|
}
|
|
7361
|
-
function
|
|
7362
|
-
|
|
7363
|
-
const
|
|
7364
|
-
if (
|
|
7404
|
+
function clearOAuth2ClientCredentials() {
|
|
7405
|
+
keychainDelete(CLIENT_ACCOUNT);
|
|
7406
|
+
const file = clientCredentialsFilePath();
|
|
7407
|
+
if (existsSync(file)) {
|
|
7408
|
+
writeAtomic0600(file, {});
|
|
7409
|
+
}
|
|
7410
|
+
}
|
|
7411
|
+
function loadOAuth2ClientCredentials() {
|
|
7412
|
+
const envId = cleanEnvValue(process.env.X_OAUTH2_CLIENT_ID) || cleanEnvValue(process.env.X_CLIENT_ID);
|
|
7413
|
+
const envSecret = cleanEnvValue(process.env.X_OAUTH2_CLIENT_SECRET) || cleanEnvValue(process.env.X_CLIENT_SECRET) || void 0;
|
|
7414
|
+
if (envId) {
|
|
7365
7415
|
return {
|
|
7366
7416
|
credentials: {
|
|
7367
|
-
|
|
7368
|
-
|
|
7417
|
+
clientId: envId,
|
|
7418
|
+
...envSecret ? { clientSecret: envSecret } : {}
|
|
7369
7419
|
},
|
|
7370
7420
|
source: "env"
|
|
7371
7421
|
};
|
|
7372
7422
|
}
|
|
7373
|
-
|
|
7423
|
+
if (detectHostConfigUi().hasNativeConfigUi && process.env.MCP_X_ARTICLES_ALLOW_KEYCHAIN_IN_NATIVE_UI !== "1") {
|
|
7424
|
+
return { credentials: null, source: "none" };
|
|
7425
|
+
}
|
|
7426
|
+
const kcRaw = keychainRead(CLIENT_ACCOUNT);
|
|
7374
7427
|
if (kcRaw) {
|
|
7375
7428
|
try {
|
|
7376
7429
|
const parsed = JSON.parse(kcRaw);
|
|
7377
|
-
if (parsed.
|
|
7430
|
+
if (parsed.clientId) {
|
|
7378
7431
|
return {
|
|
7379
7432
|
credentials: {
|
|
7380
|
-
|
|
7381
|
-
|
|
7433
|
+
clientId: parsed.clientId,
|
|
7434
|
+
...parsed.clientSecret ? { clientSecret: parsed.clientSecret } : {}
|
|
7382
7435
|
},
|
|
7383
7436
|
source: "macos-keychain"
|
|
7384
7437
|
};
|
|
@@ -7386,50 +7439,46 @@ function loadConsumerCredentials() {
|
|
|
7386
7439
|
} catch {
|
|
7387
7440
|
}
|
|
7388
7441
|
}
|
|
7389
|
-
const fileCreds = readJsonSafe(
|
|
7390
|
-
if (fileCreds?.
|
|
7442
|
+
const fileCreds = readJsonSafe(clientCredentialsFilePath());
|
|
7443
|
+
if (fileCreds?.clientId) {
|
|
7391
7444
|
return {
|
|
7392
7445
|
credentials: {
|
|
7393
|
-
|
|
7394
|
-
|
|
7446
|
+
clientId: fileCreds.clientId,
|
|
7447
|
+
...fileCreds.clientSecret ? { clientSecret: fileCreds.clientSecret } : {}
|
|
7395
7448
|
},
|
|
7396
7449
|
source: "xdg-config"
|
|
7397
7450
|
};
|
|
7398
7451
|
}
|
|
7399
7452
|
return { credentials: null, source: "none" };
|
|
7400
7453
|
}
|
|
7401
|
-
function
|
|
7454
|
+
function saveOAuth2ClientCredentials(creds) {
|
|
7455
|
+
const trimmedSecret = (creds.clientSecret ?? "").trim();
|
|
7402
7456
|
const payload = {
|
|
7403
|
-
|
|
7404
|
-
|
|
7457
|
+
clientId: creds.clientId.trim(),
|
|
7458
|
+
...trimmedSecret ? { clientSecret: trimmedSecret } : {}
|
|
7405
7459
|
};
|
|
7406
|
-
if (keychainWrite(
|
|
7460
|
+
if (keychainWrite(CLIENT_ACCOUNT, JSON.stringify(payload))) {
|
|
7407
7461
|
return "macos-keychain";
|
|
7408
7462
|
}
|
|
7409
|
-
writeAtomic0600(
|
|
7463
|
+
writeAtomic0600(clientCredentialsFilePath(), payload);
|
|
7410
7464
|
return "xdg-config";
|
|
7411
7465
|
}
|
|
7412
|
-
function
|
|
7413
|
-
const
|
|
7414
|
-
const
|
|
7415
|
-
if (envTok && envSec) {
|
|
7416
|
-
return {
|
|
7417
|
-
tokens: { accessToken: envTok, accessSecret: envSec, savedAt: 0 },
|
|
7418
|
-
source: "env"
|
|
7419
|
-
};
|
|
7420
|
-
}
|
|
7421
|
-
const keyId = consumerKeyId(consumerKey);
|
|
7422
|
-
const kcAccount = `oauth1_user_token:${keyId}`;
|
|
7466
|
+
function readStoredOAuth2UserTokens(clientId) {
|
|
7467
|
+
const keyId = clientKeyId(clientId);
|
|
7468
|
+
const kcAccount = `oauth2_user_token:${keyId}`;
|
|
7423
7469
|
const kcRaw = keychainRead(kcAccount);
|
|
7424
7470
|
if (kcRaw) {
|
|
7425
7471
|
try {
|
|
7426
7472
|
const parsed = JSON.parse(kcRaw);
|
|
7427
|
-
if (parsed.accessToken
|
|
7473
|
+
if (parsed.accessToken || parsed.refreshToken) {
|
|
7428
7474
|
return {
|
|
7429
7475
|
tokens: {
|
|
7430
|
-
accessToken: parsed.accessToken,
|
|
7431
|
-
|
|
7432
|
-
|
|
7476
|
+
accessToken: parsed.accessToken ?? "",
|
|
7477
|
+
...parsed.refreshToken ? { refreshToken: parsed.refreshToken } : {},
|
|
7478
|
+
expiresAt: Number(parsed.expiresAt ?? 0),
|
|
7479
|
+
...parsed.scope ? { scope: parsed.scope } : {},
|
|
7480
|
+
savedAt: Number(parsed.savedAt ?? 0),
|
|
7481
|
+
...parsed.seedRefreshTokenHash ? { seedRefreshTokenHash: parsed.seedRefreshTokenHash } : {}
|
|
7433
7482
|
},
|
|
7434
7483
|
source: "macos-keychain"
|
|
7435
7484
|
};
|
|
@@ -7439,26 +7488,68 @@ function loadUserOAuthTokens(consumerKey) {
|
|
|
7439
7488
|
}
|
|
7440
7489
|
const map = readJsonSafe(tokensFilePath());
|
|
7441
7490
|
const entry = map?.[keyId];
|
|
7442
|
-
if (entry
|
|
7491
|
+
if (entry && (entry.accessToken || entry.refreshToken)) {
|
|
7443
7492
|
return {
|
|
7444
7493
|
tokens: {
|
|
7445
|
-
accessToken: entry.accessToken,
|
|
7446
|
-
|
|
7447
|
-
|
|
7494
|
+
accessToken: entry.accessToken ?? "",
|
|
7495
|
+
...entry.refreshToken ? { refreshToken: entry.refreshToken } : {},
|
|
7496
|
+
expiresAt: Number(entry.expiresAt ?? 0),
|
|
7497
|
+
...entry.scope ? { scope: entry.scope } : {},
|
|
7498
|
+
savedAt: Number(entry.savedAt ?? 0),
|
|
7499
|
+
...entry.seedRefreshTokenHash ? { seedRefreshTokenHash: entry.seedRefreshTokenHash } : {}
|
|
7448
7500
|
},
|
|
7449
7501
|
source: "xdg-config"
|
|
7450
7502
|
};
|
|
7451
7503
|
}
|
|
7452
7504
|
return { tokens: null, source: "none" };
|
|
7453
7505
|
}
|
|
7454
|
-
function
|
|
7455
|
-
const
|
|
7506
|
+
function loadOAuth2UserTokens(clientId) {
|
|
7507
|
+
const stored = readStoredOAuth2UserTokens(clientId);
|
|
7508
|
+
const envRefresh = cleanEnvValue(process.env.X_OAUTH2_REFRESH_TOKEN);
|
|
7509
|
+
const envAccess = cleanEnvValue(process.env.X_OAUTH2_ACCESS_TOKEN);
|
|
7510
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
7511
|
+
if (envRefresh) {
|
|
7512
|
+
const envSeedHash = sha256Hex(envRefresh);
|
|
7513
|
+
if (stored.tokens && stored.tokens.seedRefreshTokenHash === envSeedHash) {
|
|
7514
|
+
return stored;
|
|
7515
|
+
}
|
|
7516
|
+
return {
|
|
7517
|
+
tokens: {
|
|
7518
|
+
accessToken: envAccess || "",
|
|
7519
|
+
refreshToken: envRefresh,
|
|
7520
|
+
expiresAt: envAccess ? now + 300 : 0,
|
|
7521
|
+
savedAt: 0,
|
|
7522
|
+
seedRefreshTokenHash: envSeedHash
|
|
7523
|
+
},
|
|
7524
|
+
source: "env"
|
|
7525
|
+
};
|
|
7526
|
+
}
|
|
7527
|
+
if (envAccess) {
|
|
7528
|
+
if (stored.tokens?.refreshToken && stored.tokens.accessToken) {
|
|
7529
|
+
return stored;
|
|
7530
|
+
}
|
|
7531
|
+
return {
|
|
7532
|
+
tokens: {
|
|
7533
|
+
accessToken: envAccess,
|
|
7534
|
+
expiresAt: now + 3600,
|
|
7535
|
+
savedAt: 0
|
|
7536
|
+
},
|
|
7537
|
+
source: "env"
|
|
7538
|
+
};
|
|
7539
|
+
}
|
|
7540
|
+
return stored;
|
|
7541
|
+
}
|
|
7542
|
+
function saveOAuth2UserTokens(clientId, tokens) {
|
|
7543
|
+
const keyId = clientKeyId(clientId);
|
|
7456
7544
|
const record2 = {
|
|
7457
|
-
accessToken: accessToken.trim(),
|
|
7458
|
-
|
|
7459
|
-
|
|
7545
|
+
accessToken: tokens.accessToken.trim(),
|
|
7546
|
+
...tokens.refreshToken?.trim() ? { refreshToken: tokens.refreshToken.trim() } : {},
|
|
7547
|
+
expiresAt: Math.floor(Number(tokens.expiresAt || 0)),
|
|
7548
|
+
...tokens.scope?.trim() ? { scope: tokens.scope.trim() } : {},
|
|
7549
|
+
savedAt: tokens.savedAt ?? Math.floor(Date.now() / 1e3),
|
|
7550
|
+
...tokens.seedRefreshTokenHash?.trim() ? { seedRefreshTokenHash: tokens.seedRefreshTokenHash.trim() } : {}
|
|
7460
7551
|
};
|
|
7461
|
-
if (keychainWrite(`
|
|
7552
|
+
if (keychainWrite(`oauth2_user_token:${keyId}`, JSON.stringify(record2))) {
|
|
7462
7553
|
return "macos-keychain";
|
|
7463
7554
|
}
|
|
7464
7555
|
const existing = readJsonSafe(tokensFilePath()) ?? {};
|
|
@@ -7466,9 +7557,9 @@ function saveUserOAuthTokens(consumerKey, accessToken, accessSecret) {
|
|
|
7466
7557
|
writeAtomic0600(tokensFilePath(), existing);
|
|
7467
7558
|
return "xdg-config";
|
|
7468
7559
|
}
|
|
7469
|
-
function
|
|
7470
|
-
const keyId =
|
|
7471
|
-
keychainDelete(`
|
|
7560
|
+
function clearOAuth2UserTokens(clientId) {
|
|
7561
|
+
const keyId = clientKeyId(clientId);
|
|
7562
|
+
keychainDelete(`oauth2_user_token:${keyId}`);
|
|
7472
7563
|
const file = tokensFilePath();
|
|
7473
7564
|
const existing = readJsonSafe(file);
|
|
7474
7565
|
if (existing && keyId in existing) {
|
|
@@ -7476,61 +7567,179 @@ function clearUserOAuthTokens(consumerKey) {
|
|
|
7476
7567
|
writeAtomic0600(file, existing);
|
|
7477
7568
|
}
|
|
7478
7569
|
}
|
|
7570
|
+
async function withOAuth2RefreshLock(fn) {
|
|
7571
|
+
const dir = configDirPath();
|
|
7572
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
7573
|
+
const lockPath = refreshLockFilePath();
|
|
7574
|
+
const deadline = Date.now() + REFRESH_LOCK_TIMEOUT_MS;
|
|
7575
|
+
while (true) {
|
|
7576
|
+
try {
|
|
7577
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
7578
|
+
try {
|
|
7579
|
+
writeFileSync(fd, `${process.pid}
|
|
7580
|
+
`, "utf8");
|
|
7581
|
+
} finally {
|
|
7582
|
+
closeSync(fd);
|
|
7583
|
+
}
|
|
7584
|
+
try {
|
|
7585
|
+
return await fn();
|
|
7586
|
+
} finally {
|
|
7587
|
+
rmSync(lockPath, { force: true });
|
|
7588
|
+
}
|
|
7589
|
+
} catch (err) {
|
|
7590
|
+
const code = err?.code;
|
|
7591
|
+
if (code !== "EEXIST") {
|
|
7592
|
+
throw err;
|
|
7593
|
+
}
|
|
7594
|
+
try {
|
|
7595
|
+
const st2 = statSync(lockPath);
|
|
7596
|
+
if (Date.now() - st2.mtimeMs > REFRESH_LOCK_STALE_MS) {
|
|
7597
|
+
rmSync(lockPath, { force: true });
|
|
7598
|
+
continue;
|
|
7599
|
+
}
|
|
7600
|
+
} catch {
|
|
7601
|
+
continue;
|
|
7602
|
+
}
|
|
7603
|
+
if (Date.now() >= deadline) {
|
|
7604
|
+
throw new Error(`Timed out waiting for OAuth 2.0 refresh lock at ${lockPath}.`);
|
|
7605
|
+
}
|
|
7606
|
+
await new Promise((r) => setTimeout(r, REFRESH_LOCK_POLL_MS));
|
|
7607
|
+
}
|
|
7608
|
+
}
|
|
7609
|
+
}
|
|
7479
7610
|
|
|
7480
|
-
// src/
|
|
7611
|
+
// src/oauth2.ts
|
|
7481
7612
|
import { execFile } from "node:child_process";
|
|
7482
|
-
import {
|
|
7613
|
+
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
7483
7614
|
import { createServer } from "node:http";
|
|
7484
|
-
|
|
7485
|
-
|
|
7486
|
-
|
|
7487
|
-
function rfc3986Encode(value) {
|
|
7488
|
-
return encodeURIComponent(value).replace(
|
|
7489
|
-
/[!'()*]/g,
|
|
7490
|
-
(ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`
|
|
7491
|
-
);
|
|
7615
|
+
var DEFAULT_OAUTH2_SCOPES = "tweet.read tweet.write users.read media.write offline.access";
|
|
7616
|
+
function getApiBaseUrl() {
|
|
7617
|
+
return (process.env.X_API_BASE_URL ?? "https://api.x.com").trim().replace(/\/+$/, "");
|
|
7492
7618
|
}
|
|
7493
|
-
function
|
|
7494
|
-
|
|
7495
|
-
|
|
7496
|
-
|
|
7497
|
-
const
|
|
7498
|
-
|
|
7499
|
-
|
|
7500
|
-
|
|
7501
|
-
|
|
7502
|
-
|
|
7503
|
-
|
|
7504
|
-
|
|
7619
|
+
function getOAuth2AuthorizeUrl() {
|
|
7620
|
+
return (process.env.X_OAUTH2_AUTHORIZE_URL ?? "https://x.com/i/oauth2/authorize").trim().replace(/\/+$/, "");
|
|
7621
|
+
}
|
|
7622
|
+
function getOAuth2TokenUrl() {
|
|
7623
|
+
const override = (process.env.X_OAUTH2_TOKEN_URL ?? "").trim();
|
|
7624
|
+
if (override) return override.replace(/\/+$/, "");
|
|
7625
|
+
return `${getApiBaseUrl()}/2/oauth2/token`;
|
|
7626
|
+
}
|
|
7627
|
+
function getOAuth2Scopes() {
|
|
7628
|
+
const override = (process.env.X_OAUTH2_SCOPES ?? "").trim();
|
|
7629
|
+
return override || DEFAULT_OAUTH2_SCOPES;
|
|
7630
|
+
}
|
|
7631
|
+
function generatePkcePair() {
|
|
7632
|
+
const codeVerifier = randomBytes(64).toString("base64url");
|
|
7633
|
+
const codeChallenge = createHash2("sha256").update(codeVerifier, "utf8").digest("base64url");
|
|
7634
|
+
return { codeVerifier, codeChallenge };
|
|
7635
|
+
}
|
|
7636
|
+
function buildOAuth2AuthorizeUrl(params) {
|
|
7637
|
+
const url = new URL(getOAuth2AuthorizeUrl());
|
|
7638
|
+
url.searchParams.set("response_type", "code");
|
|
7639
|
+
url.searchParams.set("client_id", params.clientId);
|
|
7640
|
+
url.searchParams.set("redirect_uri", params.redirectUri);
|
|
7641
|
+
url.searchParams.set("scope", params.scopes?.trim() || getOAuth2Scopes());
|
|
7642
|
+
url.searchParams.set("state", params.state);
|
|
7643
|
+
url.searchParams.set("code_challenge", params.codeChallenge);
|
|
7644
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
7645
|
+
return url.toString();
|
|
7646
|
+
}
|
|
7647
|
+
var OAuth2TokenError = class extends Error {
|
|
7648
|
+
status;
|
|
7649
|
+
oauthError;
|
|
7650
|
+
rawBody;
|
|
7651
|
+
constructor(message, status, oauthError, rawBody = "") {
|
|
7652
|
+
super(message);
|
|
7653
|
+
this.name = "OAuth2TokenError";
|
|
7654
|
+
this.status = status;
|
|
7655
|
+
this.oauthError = oauthError;
|
|
7656
|
+
this.rawBody = rawBody;
|
|
7657
|
+
}
|
|
7658
|
+
};
|
|
7659
|
+
async function postTokenEndpoint(options) {
|
|
7660
|
+
const tokenUrl = getOAuth2TokenUrl();
|
|
7661
|
+
const body = new URLSearchParams();
|
|
7662
|
+
const headers = {
|
|
7663
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
7505
7664
|
};
|
|
7506
|
-
|
|
7507
|
-
|
|
7508
|
-
|
|
7665
|
+
if (options.credentials.clientSecret) {
|
|
7666
|
+
const basic = Buffer.from(
|
|
7667
|
+
`${options.credentials.clientId}:${options.credentials.clientSecret}`,
|
|
7668
|
+
"utf8"
|
|
7669
|
+
).toString("base64");
|
|
7670
|
+
headers.Authorization = `Basic ${basic}`;
|
|
7671
|
+
} else {
|
|
7672
|
+
body.set("client_id", options.credentials.clientId);
|
|
7509
7673
|
}
|
|
7510
|
-
for (const [k, v2] of
|
|
7511
|
-
|
|
7674
|
+
for (const [k, v2] of Object.entries(options.params)) {
|
|
7675
|
+
body.set(k, v2);
|
|
7512
7676
|
}
|
|
7513
|
-
|
|
7514
|
-
|
|
7515
|
-
|
|
7677
|
+
const resp = await fetch(tokenUrl, {
|
|
7678
|
+
method: "POST",
|
|
7679
|
+
headers,
|
|
7680
|
+
body: body.toString()
|
|
7681
|
+
});
|
|
7682
|
+
const text = await resp.text();
|
|
7683
|
+
let parsed = {};
|
|
7684
|
+
if (text.trim()) {
|
|
7685
|
+
try {
|
|
7686
|
+
parsed = JSON.parse(text);
|
|
7687
|
+
} catch {
|
|
7688
|
+
parsed = { raw: text };
|
|
7516
7689
|
}
|
|
7517
7690
|
}
|
|
7518
|
-
|
|
7519
|
-
|
|
7520
|
-
|
|
7691
|
+
if (!resp.ok) {
|
|
7692
|
+
const oauthErr = typeof parsed.error === "string" ? parsed.error : typeof parsed.title === "string" ? parsed.title : void 0;
|
|
7693
|
+
const desc = typeof parsed.error_description === "string" ? parsed.error_description : typeof parsed.detail === "string" ? parsed.detail : text;
|
|
7694
|
+
throw new OAuth2TokenError(
|
|
7695
|
+
`X OAuth 2.0 token request failed (HTTP ${resp.status}${oauthErr ? `, ${oauthErr}` : ""}): ${desc}`,
|
|
7696
|
+
resp.status,
|
|
7697
|
+
oauthErr,
|
|
7698
|
+
text
|
|
7699
|
+
);
|
|
7700
|
+
}
|
|
7701
|
+
const accessToken = typeof parsed.access_token === "string" ? parsed.access_token.trim() : "";
|
|
7702
|
+
if (!accessToken) {
|
|
7703
|
+
throw new OAuth2TokenError(
|
|
7704
|
+
`X OAuth 2.0 token response did not contain access_token: ${text}`,
|
|
7705
|
+
resp.status,
|
|
7706
|
+
void 0,
|
|
7707
|
+
text
|
|
7708
|
+
);
|
|
7709
|
+
}
|
|
7710
|
+
const refreshToken = typeof parsed.refresh_token === "string" && parsed.refresh_token.trim() ? parsed.refresh_token.trim() : void 0;
|
|
7711
|
+
const expiresIn = Math.max(60, Number(parsed.expires_in ?? 7200) || 7200);
|
|
7712
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
7713
|
+
const scope = typeof parsed.scope === "string" ? parsed.scope.trim() : void 0;
|
|
7714
|
+
const tokenType = typeof parsed.token_type === "string" ? parsed.token_type.trim() : void 0;
|
|
7715
|
+
return {
|
|
7716
|
+
accessToken,
|
|
7717
|
+
refreshToken,
|
|
7718
|
+
expiresIn,
|
|
7719
|
+
expiresAt: now + expiresIn,
|
|
7720
|
+
scope,
|
|
7721
|
+
tokenType
|
|
7722
|
+
};
|
|
7723
|
+
}
|
|
7724
|
+
async function exchangeAuthorizationCode(options) {
|
|
7725
|
+
return postTokenEndpoint({
|
|
7726
|
+
credentials: options.credentials,
|
|
7727
|
+
params: {
|
|
7728
|
+
grant_type: "authorization_code",
|
|
7729
|
+
code: options.code,
|
|
7730
|
+
redirect_uri: options.redirectUri,
|
|
7731
|
+
code_verifier: options.codeVerifier
|
|
7732
|
+
}
|
|
7733
|
+
});
|
|
7734
|
+
}
|
|
7735
|
+
async function refreshOAuth2Token(options) {
|
|
7736
|
+
return postTokenEndpoint({
|
|
7737
|
+
credentials: options.credentials,
|
|
7738
|
+
params: {
|
|
7739
|
+
grant_type: "refresh_token",
|
|
7740
|
+
refresh_token: options.refreshToken
|
|
7741
|
+
}
|
|
7521
7742
|
});
|
|
7522
|
-
const normalizedParams = pairs.map(([k, v2]) => `${k}=${v2}`).join("&");
|
|
7523
|
-
const baseString = `${method}&${rfc3986Encode(baseUri)}&${rfc3986Encode(normalizedParams)}`;
|
|
7524
|
-
const signingKey = `${rfc3986Encode(options.credentials.consumerSecret)}&${rfc3986Encode(
|
|
7525
|
-
options.credentials.tokenSecret ?? ""
|
|
7526
|
-
)}`;
|
|
7527
|
-
const signature = createHmac("sha1", signingKey).update(baseString, "utf8").digest("base64");
|
|
7528
|
-
const headerEntries = [
|
|
7529
|
-
...Object.entries(oauthParams),
|
|
7530
|
-
["oauth_signature", signature]
|
|
7531
|
-
].sort((a, b2) => a[0] < b2[0] ? -1 : a[0] > b2[0] ? 1 : 0);
|
|
7532
|
-
const headerBody = headerEntries.map(([k, v2]) => `${rfc3986Encode(k)}="${rfc3986Encode(v2)}"`).join(", ");
|
|
7533
|
-
return `OAuth ${headerBody}`;
|
|
7534
7743
|
}
|
|
7535
7744
|
function openBrowserUrl(targetUrl) {
|
|
7536
7745
|
if (process.env.MCP_X_ARTICLES_NO_BROWSER === "1") return;
|
|
@@ -7548,7 +7757,7 @@ function openBrowserUrl(targetUrl) {
|
|
|
7548
7757
|
function escapeHtml(raw) {
|
|
7549
7758
|
return raw.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
7550
7759
|
}
|
|
7551
|
-
function renderHtmlPage(title, bodyHtml
|
|
7760
|
+
function renderHtmlPage(title, bodyHtml) {
|
|
7552
7761
|
return `<!DOCTYPE html>
|
|
7553
7762
|
<html lang="en">
|
|
7554
7763
|
<head>
|
|
@@ -7559,420 +7768,346 @@ function renderHtmlPage(title, bodyHtml, allowOpenLink = false) {
|
|
|
7559
7768
|
:root { color-scheme: light dark; }
|
|
7560
7769
|
body {
|
|
7561
7770
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
7562
|
-
|
|
7563
|
-
|
|
7564
|
-
|
|
7771
|
+
max-width: 560px;
|
|
7772
|
+
margin: 48px auto;
|
|
7773
|
+
padding: 0 20px;
|
|
7774
|
+
line-height: 1.55;
|
|
7565
7775
|
}
|
|
7566
7776
|
.card {
|
|
7567
|
-
|
|
7568
|
-
border
|
|
7569
|
-
padding:
|
|
7570
|
-
|
|
7571
|
-
|
|
7572
|
-
|
|
7573
|
-
|
|
7777
|
+
border: 1px solid rgba(128,128,128,0.28);
|
|
7778
|
+
border-radius: 14px;
|
|
7779
|
+
padding: 26px 28px;
|
|
7780
|
+
background: rgba(128,128,128,0.05);
|
|
7781
|
+
}
|
|
7782
|
+
h1 { font-size: 20px; margin: 0 0 8px; }
|
|
7783
|
+
p.sub { opacity: 0.8; margin: 0 0 18px; font-size: 14px; }
|
|
7784
|
+
label { display: block; font-weight: 600; font-size: 13px; margin: 14px 0 6px; }
|
|
7574
7785
|
input[type="text"], input[type="password"] {
|
|
7575
|
-
width: 100%;
|
|
7576
|
-
|
|
7577
|
-
|
|
7578
|
-
|
|
7579
|
-
|
|
7580
|
-
|
|
7581
|
-
|
|
7582
|
-
background:
|
|
7583
|
-
|
|
7584
|
-
|
|
7585
|
-
|
|
7586
|
-
|
|
7786
|
+
width: 100%;
|
|
7787
|
+
box-sizing: border-box;
|
|
7788
|
+
padding: 10px 12px;
|
|
7789
|
+
font-size: 14px;
|
|
7790
|
+
border: 1px solid rgba(128,128,128,0.38);
|
|
7791
|
+
border-radius: 8px;
|
|
7792
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
7793
|
+
background: transparent;
|
|
7794
|
+
}
|
|
7795
|
+
button {
|
|
7796
|
+
margin-top: 20px;
|
|
7797
|
+
width: 100%;
|
|
7798
|
+
padding: 11px 16px;
|
|
7799
|
+
font-size: 15px;
|
|
7800
|
+
font-weight: 600;
|
|
7801
|
+
border-radius: 9px;
|
|
7802
|
+
border: none;
|
|
7803
|
+
cursor: pointer;
|
|
7804
|
+
background: #eff3f4;
|
|
7805
|
+
color: #0f1419;
|
|
7806
|
+
}
|
|
7807
|
+
@media (prefers-color-scheme: light) {
|
|
7808
|
+
button { background: #0f1419; color: #ffffff; }
|
|
7587
7809
|
}
|
|
7588
7810
|
.err {
|
|
7589
|
-
|
|
7590
|
-
|
|
7591
|
-
|
|
7592
|
-
|
|
7811
|
+
margin-bottom: 14px;
|
|
7812
|
+
padding: 10px 12px;
|
|
7813
|
+
border-radius: 8px;
|
|
7814
|
+
border: 1px solid rgba(244,33,46,0.5);
|
|
7815
|
+
background: rgba(244,33,46,0.08);
|
|
7816
|
+
font-size: 13px;
|
|
7817
|
+
}
|
|
7818
|
+
.hint { font-size: 12px; opacity: 0.72; margin-top: 12px; }
|
|
7819
|
+
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
|
7593
7820
|
</style>
|
|
7594
7821
|
</head>
|
|
7595
7822
|
<body>
|
|
7596
7823
|
<div class="card">
|
|
7597
7824
|
${bodyHtml}
|
|
7598
7825
|
</div>
|
|
7599
|
-
${allowOpenLink ? "" : ""}
|
|
7600
7826
|
</body>
|
|
7601
7827
|
</html>`;
|
|
7602
7828
|
}
|
|
7829
|
+
function sendHtml(res, status, title, bodyHtml) {
|
|
7830
|
+
const html = renderHtmlPage(title, bodyHtml);
|
|
7831
|
+
res.writeHead(status, {
|
|
7832
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
7833
|
+
"Cache-Control": "no-store"
|
|
7834
|
+
});
|
|
7835
|
+
res.end(html);
|
|
7836
|
+
}
|
|
7603
7837
|
async function readFormBody(req) {
|
|
7604
7838
|
const chunks = [];
|
|
7605
7839
|
let total = 0;
|
|
7606
7840
|
for await (const chunk of req) {
|
|
7607
|
-
const buf =
|
|
7841
|
+
const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
7608
7842
|
total += buf.length;
|
|
7609
7843
|
if (total > 32 * 1024) {
|
|
7610
|
-
throw new Error("
|
|
7844
|
+
throw new Error("Request body too large.");
|
|
7611
7845
|
}
|
|
7612
7846
|
chunks.push(buf);
|
|
7613
7847
|
}
|
|
7614
7848
|
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
7615
7849
|
}
|
|
7616
|
-
|
|
7617
|
-
const
|
|
7618
|
-
|
|
7619
|
-
|
|
7620
|
-
|
|
7621
|
-
|
|
7622
|
-
|
|
7623
|
-
|
|
7624
|
-
|
|
7625
|
-
|
|
7626
|
-
|
|
7627
|
-
});
|
|
7628
|
-
const body = await resp.text();
|
|
7629
|
-
if (!resp.ok) {
|
|
7630
|
-
return { ok: false, status: resp.status, body };
|
|
7631
|
-
}
|
|
7632
|
-
const params = new URLSearchParams(body);
|
|
7633
|
-
const requestToken = params.get("oauth_token") ?? "";
|
|
7634
|
-
const requestTokenSecret = params.get("oauth_token_secret") ?? "";
|
|
7635
|
-
if (!requestToken || !requestTokenSecret) {
|
|
7636
|
-
return { ok: false, status: 500, body: `Malformed request_token response: ${body}` };
|
|
7637
|
-
}
|
|
7638
|
-
return { ok: true, requestToken, requestTokenSecret };
|
|
7639
|
-
}
|
|
7640
|
-
async function exchangeXAccessToken(options) {
|
|
7641
|
-
const url = `${getOAuthBaseUrl()}/oauth/access_token`;
|
|
7642
|
-
const auth = signOAuth1Header({
|
|
7643
|
-
method: "POST",
|
|
7644
|
-
url,
|
|
7645
|
-
credentials: {
|
|
7646
|
-
consumerKey: options.consumerKey,
|
|
7647
|
-
consumerSecret: options.consumerSecret,
|
|
7648
|
-
tokenKey: options.requestToken,
|
|
7649
|
-
tokenSecret: options.requestTokenSecret
|
|
7650
|
-
},
|
|
7651
|
-
extraOAuthParams: { oauth_verifier: options.verifier }
|
|
7652
|
-
});
|
|
7653
|
-
const resp = await fetch(url, {
|
|
7654
|
-
method: "POST",
|
|
7655
|
-
headers: { Authorization: auth }
|
|
7656
|
-
});
|
|
7657
|
-
const body = await resp.text();
|
|
7658
|
-
if (!resp.ok) {
|
|
7659
|
-
throw new Error(`Failed to exchange X OAuth access token (HTTP ${resp.status}): ${body}`);
|
|
7660
|
-
}
|
|
7661
|
-
const params = new URLSearchParams(body);
|
|
7662
|
-
const accessToken = params.get("oauth_token") ?? "";
|
|
7663
|
-
const accessSecret = params.get("oauth_token_secret") ?? "";
|
|
7664
|
-
if (!accessToken || !accessSecret) {
|
|
7665
|
-
throw new Error(`Malformed X OAuth access_token response: ${body}`);
|
|
7666
|
-
}
|
|
7667
|
-
return { accessToken, accessSecret };
|
|
7668
|
-
}
|
|
7669
|
-
async function listenWithRandomFallback(server, host, preferredPort) {
|
|
7670
|
-
if (preferredPort > 0) {
|
|
7671
|
-
try {
|
|
7672
|
-
await new Promise((resolveListen, rejectListen) => {
|
|
7673
|
-
const onErr = (err) => {
|
|
7674
|
-
server.off("listening", onListening);
|
|
7675
|
-
rejectListen(err);
|
|
7676
|
-
};
|
|
7677
|
-
const onListening = () => {
|
|
7678
|
-
server.off("error", onErr);
|
|
7679
|
-
resolveListen();
|
|
7680
|
-
};
|
|
7681
|
-
server.once("error", onErr);
|
|
7682
|
-
server.once("listening", onListening);
|
|
7683
|
-
server.listen(preferredPort, host);
|
|
7684
|
-
});
|
|
7685
|
-
const addr2 = server.address();
|
|
7686
|
-
return { actualPort: addr2.port, usedFallbackPort: false };
|
|
7687
|
-
} catch (err) {
|
|
7688
|
-
const code = err?.code;
|
|
7689
|
-
if (code !== "EADDRINUSE" && code !== "EACCES") {
|
|
7690
|
-
throw err;
|
|
7691
|
-
}
|
|
7692
|
-
process.stderr.write(
|
|
7693
|
-
`[@wezzard/mcp-x-articles] Port ${preferredPort} is in use; falling back to an OS-assigned random port with OAuth 1.0a PIN mode.
|
|
7694
|
-
`
|
|
7695
|
-
);
|
|
7696
|
-
}
|
|
7850
|
+
function resolveCallbackConfig() {
|
|
7851
|
+
const explicitRedirect = (process.env.X_OAUTH_REDIRECT_URI ?? "").trim();
|
|
7852
|
+
if (explicitRedirect) {
|
|
7853
|
+
const parsed = new URL(explicitRedirect);
|
|
7854
|
+
const port2 = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
|
|
7855
|
+
return {
|
|
7856
|
+
host: parsed.hostname || "127.0.0.1",
|
|
7857
|
+
port: port2,
|
|
7858
|
+
callbackPath: parsed.pathname || "/oauth/callback",
|
|
7859
|
+
explicitRedirectUri: explicitRedirect
|
|
7860
|
+
};
|
|
7697
7861
|
}
|
|
7698
|
-
await new Promise((resolveListen, rejectListen) => {
|
|
7699
|
-
server.once("error", rejectListen);
|
|
7700
|
-
server.listen(0, host, () => {
|
|
7701
|
-
server.off("error", rejectListen);
|
|
7702
|
-
resolveListen();
|
|
7703
|
-
});
|
|
7704
|
-
});
|
|
7705
|
-
const addr = server.address();
|
|
7706
|
-
return { actualPort: addr.port, usedFallbackPort: true };
|
|
7707
|
-
}
|
|
7708
|
-
async function runInteractiveSetupAndOAuth1Flow(options) {
|
|
7709
7862
|
const host = (process.env.X_OAUTH_CALLBACK_HOST ?? "127.0.0.1").trim() || "127.0.0.1";
|
|
7710
7863
|
const rawPort = (process.env.X_OAUTH_CALLBACK_PORT ?? "8976").trim();
|
|
7711
|
-
const
|
|
7712
|
-
const
|
|
7713
|
-
const
|
|
7714
|
-
|
|
7715
|
-
|
|
7716
|
-
|
|
7717
|
-
|
|
7718
|
-
|
|
7719
|
-
|
|
7720
|
-
|
|
7721
|
-
const sendHtml = (res, status, html) => {
|
|
7722
|
-
res.statusCode = status;
|
|
7723
|
-
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
7724
|
-
res.setHeader("Cache-Control", "no-store");
|
|
7725
|
-
res.setHeader(
|
|
7726
|
-
"Content-Security-Policy",
|
|
7727
|
-
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'"
|
|
7864
|
+
const port = rawPort === "0" ? 0 : Number(rawPort || 8976);
|
|
7865
|
+
const rawPath = (process.env.X_OAUTH_CALLBACK_PATH ?? "/oauth/callback").trim();
|
|
7866
|
+
const callbackPath = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
|
|
7867
|
+
return { host, port, callbackPath };
|
|
7868
|
+
}
|
|
7869
|
+
async function runInteractiveSetupAndOAuth2Flow(options) {
|
|
7870
|
+
const hostUi = detectHostConfigUi();
|
|
7871
|
+
if (!options.existingCredentials && hostUi.hasNativeConfigUi) {
|
|
7872
|
+
throw new Error(
|
|
7873
|
+
`Missing X OAuth 2.0 Client ID. Because you are running inside ${hostUi.hostName}, configure X_OAUTH2_CLIENT_ID (and optional X_OAUTH2_CLIENT_SECRET / X_OAUTH2_REFRESH_TOKEN) in the native plugin settings UI (${hostUi.configUiUrl ?? hostUi.hostName}) rather than the localhost setup page.`
|
|
7728
7874
|
);
|
|
7729
|
-
|
|
7730
|
-
};
|
|
7731
|
-
|
|
7732
|
-
let
|
|
7875
|
+
}
|
|
7876
|
+
const { host, port, callbackPath, explicitRedirectUri } = resolveCallbackConfig();
|
|
7877
|
+
const timeoutSec = Math.max(30, Number(process.env.X_OAUTH_CALLBACK_TIMEOUT ?? 300) || 300);
|
|
7878
|
+
let credentials = options.existingCredentials;
|
|
7879
|
+
let credentialSource = options.existingCredentialSource;
|
|
7880
|
+
const csrfToken = randomBytes(16).toString("hex");
|
|
7881
|
+
const pkce = generatePkcePair();
|
|
7882
|
+
const oauthState = randomBytes(24).toString("hex");
|
|
7883
|
+
let boundPort = port;
|
|
7884
|
+
let activeRedirectUri = explicitRedirectUri ?? `http://${host}:${port}${callbackPath}`;
|
|
7885
|
+
let finishResolve;
|
|
7886
|
+
let finishReject;
|
|
7733
7887
|
const donePromise = new Promise((res, rej) => {
|
|
7734
|
-
|
|
7735
|
-
|
|
7888
|
+
finishResolve = res;
|
|
7889
|
+
finishReject = rej;
|
|
7736
7890
|
});
|
|
7737
|
-
const
|
|
7738
|
-
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
cbUrl
|
|
7744
|
-
);
|
|
7745
|
-
if (attempt.ok) {
|
|
7746
|
-
activeReqToken = attempt.requestToken;
|
|
7747
|
-
activeReqSecret = attempt.requestTokenSecret;
|
|
7748
|
-
return `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7749
|
-
}
|
|
7750
|
-
if (attempt.body.toLowerCase().includes("callback") || attempt.status === 401 || attempt.status === 403 || attempt.status === 400) {
|
|
7751
|
-
const oobAttempt = await requestXToken(
|
|
7752
|
-
currentCreds.consumerKey,
|
|
7753
|
-
currentCreds.consumerSecret,
|
|
7754
|
-
"oob"
|
|
7755
|
-
);
|
|
7756
|
-
if (oobAttempt.ok) {
|
|
7757
|
-
useOobMode = true;
|
|
7758
|
-
activeReqToken = oobAttempt.requestToken;
|
|
7759
|
-
activeReqSecret = oobAttempt.requestTokenSecret;
|
|
7760
|
-
return `http://${host}:${actualPort}/pin?s=${csrfSecret}`;
|
|
7761
|
-
}
|
|
7762
|
-
}
|
|
7763
|
-
throw new Error(`X OAuth request_token failed (HTTP ${attempt.status}): ${attempt.body}`);
|
|
7764
|
-
}
|
|
7765
|
-
const oobRes = await requestXToken(
|
|
7766
|
-
currentCreds.consumerKey,
|
|
7767
|
-
currentCreds.consumerSecret,
|
|
7768
|
-
"oob"
|
|
7769
|
-
);
|
|
7770
|
-
if (!oobRes.ok) {
|
|
7771
|
-
throw new Error(`X OAuth request_token (oob) failed (HTTP ${oobRes.status}): ${oobRes.body}`);
|
|
7772
|
-
}
|
|
7773
|
-
activeReqToken = oobRes.requestToken;
|
|
7774
|
-
activeReqSecret = oobRes.requestTokenSecret;
|
|
7775
|
-
return `http://${host}:${actualPort}/pin?s=${csrfSecret}`;
|
|
7776
|
-
};
|
|
7777
|
-
const renderSetupForm = (errorMsg) => renderHtmlPage(
|
|
7778
|
-
"Setup @wezzard/mcp-x-articles",
|
|
7779
|
-
[
|
|
7780
|
-
"<h1>Connect @wezzard/mcp-x-articles</h1>",
|
|
7781
|
-
"<p>Enter your X Developer App keys from <code>https://console.x.com</code>. They are saved directly into your local OS Keychain and never sent to any AI model.</p>",
|
|
7782
|
-
errorMsg ? `<div class="err">${escapeHtml(errorMsg)}</div>` : "",
|
|
7783
|
-
'<form method="POST" action="/setup">',
|
|
7784
|
-
`<input type="hidden" name="s" value="${csrfSecret}" />`,
|
|
7785
|
-
'<label for="ck">X API Key (Consumer Key)</label>',
|
|
7786
|
-
'<input id="ck" name="consumer_key" type="text" autocomplete="off" required />',
|
|
7787
|
-
'<label for="cs">X API Key Secret (Consumer Secret)</label>',
|
|
7788
|
-
'<input id="cs" name="consumer_secret" type="password" autocomplete="off" required />',
|
|
7789
|
-
'<button type="submit">Save to Keychain & Authorize on X →</button>',
|
|
7790
|
-
"</form>"
|
|
7791
|
-
].join("\n")
|
|
7792
|
-
);
|
|
7793
|
-
const renderPinForm = (authorizeUrl, errorMsg) => renderHtmlPage(
|
|
7794
|
-
"Authorize @wezzard/mcp-x-articles",
|
|
7795
|
-
[
|
|
7796
|
-
"<h1>Enter Your X Authorization PIN</h1>",
|
|
7797
|
-
"<p>1. Open X in a new tab and click <strong>Authorize app</strong>.<br/>2. Copy the 7-digit PIN displayed by X and paste it below.</p>",
|
|
7798
|
-
`<p><a class="btn" href="${escapeHtml(authorizeUrl)}" target="_blank" rel="noopener noreferrer">1. Open X Authorization Page ↗</a></p>`,
|
|
7799
|
-
errorMsg ? `<div class="err">${escapeHtml(errorMsg)}</div>` : "",
|
|
7800
|
-
'<form method="POST" action="/pin">',
|
|
7801
|
-
`<input type="hidden" name="s" value="${csrfSecret}" />`,
|
|
7802
|
-
'<label for="pin">2. X OAuth PIN Code</label>',
|
|
7803
|
-
'<input id="pin" name="verifier" type="text" inputmode="numeric" autocomplete="one-time-code" placeholder="1234567" required />',
|
|
7804
|
-
'<button type="submit">Complete Authentication</button>',
|
|
7805
|
-
"</form>"
|
|
7806
|
-
].join("\n"),
|
|
7807
|
-
true
|
|
7808
|
-
);
|
|
7809
|
-
const server = createServer(async (req, res) => {
|
|
7810
|
-
try {
|
|
7811
|
-
const reqUrl = new URL(req.url ?? "/", `http://${host}:${actualPort}`);
|
|
7812
|
-
if (req.method === "GET" && reqUrl.pathname === "/setup") {
|
|
7813
|
-
if (reqUrl.searchParams.get("s") !== csrfSecret) {
|
|
7814
|
-
sendHtml(res, 403, renderHtmlPage("Forbidden", "<h1>Invalid setup session token.</h1>"));
|
|
7815
|
-
return;
|
|
7816
|
-
}
|
|
7817
|
-
sendHtml(res, 200, renderSetupForm());
|
|
7891
|
+
const handleRequest = async (req, res) => {
|
|
7892
|
+
const reqUrl = new URL(req.url ?? "/", `http://${host}:${boundPort}`);
|
|
7893
|
+
const path = reqUrl.pathname;
|
|
7894
|
+
if (req.method === "GET" && path === "/setup") {
|
|
7895
|
+
if (reqUrl.searchParams.get("s") !== csrfToken) {
|
|
7896
|
+
sendHtml(res, 403, "Session Expired", "<h1>Session expired</h1><p>Restart login.</p>");
|
|
7818
7897
|
return;
|
|
7819
7898
|
}
|
|
7820
|
-
|
|
7821
|
-
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
|
|
7826
|
-
|
|
7827
|
-
|
|
7828
|
-
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
|
|
7834
|
-
|
|
7835
|
-
|
|
7836
|
-
|
|
7837
|
-
|
|
7838
|
-
|
|
7839
|
-
|
|
7840
|
-
|
|
7841
|
-
|
|
7842
|
-
|
|
7843
|
-
|
|
7899
|
+
const errMsg = reqUrl.searchParams.get("error") ?? "";
|
|
7900
|
+
const errBlock = errMsg ? `<div class="err">${escapeHtml(errMsg)}</div>` : "";
|
|
7901
|
+
sendHtml(
|
|
7902
|
+
res,
|
|
7903
|
+
200,
|
|
7904
|
+
"Connect @wezzard/mcp-x-articles (OAuth 2.0)",
|
|
7905
|
+
`
|
|
7906
|
+
<h1>Connect @wezzard/mcp-x-articles</h1>
|
|
7907
|
+
<p class="sub">
|
|
7908
|
+
Enter your <strong>OAuth 2.0 Keys</strong> from
|
|
7909
|
+
<code>https://console.x.com</code> → Keys & Tokens.
|
|
7910
|
+
Credentials are stored locally in your OS Keychain.
|
|
7911
|
+
</p>
|
|
7912
|
+
${errBlock}
|
|
7913
|
+
<form method="POST" action="/setup">
|
|
7914
|
+
<input type="hidden" name="s" value="${escapeHtml(csrfToken)}" />
|
|
7915
|
+
<label for="client_id">X OAuth 2.0 Client ID</label>
|
|
7916
|
+
<input id="client_id" name="client_id" type="text" required autocomplete="off"
|
|
7917
|
+
value="${escapeHtml(credentials?.clientId ?? "")}"
|
|
7918
|
+
placeholder="Paste OAuth 2.0 Client ID" />
|
|
7919
|
+
<label for="client_secret">X OAuth 2.0 Client Secret (Optional for public clients)</label>
|
|
7920
|
+
<input id="client_secret" name="client_secret" type="password" autocomplete="off"
|
|
7921
|
+
placeholder="Paste Client Secret (or leave blank if public)" />
|
|
7922
|
+
<label for="refresh_token">X OAuth 2.0 Refresh Token (Optional \u2014 skip browser callback)</label>
|
|
7923
|
+
<input id="refresh_token" name="refresh_token" type="password" autocomplete="off"
|
|
7924
|
+
placeholder="Paste from Console 'Generate', or leave blank for PKCE login" />
|
|
7925
|
+
<button type="submit">Save to Keychain & Authorize on X →</button>
|
|
7926
|
+
</form>
|
|
7927
|
+
<p class="hint">
|
|
7928
|
+
For browser PKCE login, register callback URI:
|
|
7929
|
+
<code>${escapeHtml(activeRedirectUri)}</code>
|
|
7930
|
+
</p>
|
|
7931
|
+
`
|
|
7932
|
+
);
|
|
7933
|
+
return;
|
|
7934
|
+
}
|
|
7935
|
+
if (req.method === "POST" && path === "/setup") {
|
|
7936
|
+
const form = await readFormBody(req);
|
|
7937
|
+
if (form.get("s") !== csrfToken) {
|
|
7938
|
+
sendHtml(res, 403, "Session Expired", "<h1>Session expired</h1><p>Restart login.</p>");
|
|
7844
7939
|
return;
|
|
7845
7940
|
}
|
|
7846
|
-
|
|
7847
|
-
|
|
7848
|
-
|
|
7849
|
-
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
|
|
7941
|
+
const clientId = (form.get("client_id") ?? "").trim();
|
|
7942
|
+
const clientSecret = (form.get("client_secret") ?? "").trim() || void 0;
|
|
7943
|
+
const refreshToken = (form.get("refresh_token") ?? "").trim();
|
|
7944
|
+
if (!clientId) {
|
|
7945
|
+
res.writeHead(302, {
|
|
7946
|
+
Location: `/setup?s=${csrfToken}&error=${encodeURIComponent("Client ID is required.")}`
|
|
7947
|
+
});
|
|
7948
|
+
res.end();
|
|
7853
7949
|
return;
|
|
7854
7950
|
}
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
|
|
7858
|
-
|
|
7859
|
-
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
if (!verifier) {
|
|
7863
|
-
const authUrl = `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7864
|
-
sendHtml(res, 400, renderPinForm(authUrl, "Please enter the PIN code from X."));
|
|
7865
|
-
return;
|
|
7866
|
-
}
|
|
7951
|
+
const nextCreds = {
|
|
7952
|
+
clientId,
|
|
7953
|
+
...clientSecret ? { clientSecret } : {}
|
|
7954
|
+
};
|
|
7955
|
+
credentialSource = saveOAuth2ClientCredentials(nextCreds);
|
|
7956
|
+
credentials = nextCreds;
|
|
7957
|
+
if (refreshToken) {
|
|
7867
7958
|
try {
|
|
7868
|
-
const
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7959
|
+
const tokenResp = await refreshOAuth2Token({
|
|
7960
|
+
credentials: nextCreds,
|
|
7961
|
+
refreshToken
|
|
7962
|
+
});
|
|
7963
|
+
const nextRefresh = tokenResp.refreshToken ?? refreshToken;
|
|
7964
|
+
const seedHash = sha256Hex(refreshToken);
|
|
7965
|
+
const tokenSource = saveOAuth2UserTokens(nextCreds.clientId, {
|
|
7966
|
+
accessToken: tokenResp.accessToken,
|
|
7967
|
+
refreshToken: nextRefresh,
|
|
7968
|
+
expiresAt: tokenResp.expiresAt,
|
|
7969
|
+
scope: tokenResp.scope,
|
|
7970
|
+
seedRefreshTokenHash: seedHash
|
|
7874
7971
|
});
|
|
7875
7972
|
sendHtml(
|
|
7876
7973
|
res,
|
|
7877
7974
|
200,
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
"<h1>Authentication Complete</h1><p>Your X credentials and token are saved in your local Keychain. You may close this tab and return to your agent.</p>"
|
|
7881
|
-
)
|
|
7975
|
+
"X Connected",
|
|
7976
|
+
"<h1>Authorized!</h1><p>Your OAuth 2.0 tokens have been refreshed and saved. You can close this tab and return to your agent.</p>"
|
|
7882
7977
|
);
|
|
7883
|
-
|
|
7884
|
-
|
|
7885
|
-
|
|
7886
|
-
|
|
7887
|
-
|
|
7888
|
-
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7978
|
+
finishResolve({
|
|
7979
|
+
credentials: nextCreds,
|
|
7980
|
+
credentialSource,
|
|
7981
|
+
tokenSource,
|
|
7982
|
+
accessToken: tokenResp.accessToken,
|
|
7983
|
+
refreshToken: nextRefresh,
|
|
7984
|
+
expiresAt: tokenResp.expiresAt,
|
|
7985
|
+
scope: tokenResp.scope,
|
|
7986
|
+
redirectUri: activeRedirectUri,
|
|
7987
|
+
seedRefreshTokenHash: seedHash
|
|
7893
7988
|
});
|
|
7894
7989
|
} catch (err) {
|
|
7895
|
-
const authUrl = `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7896
7990
|
const msg = err instanceof Error ? err.message : String(err);
|
|
7897
|
-
|
|
7991
|
+
res.writeHead(302, {
|
|
7992
|
+
Location: `/setup?s=${csrfToken}&error=${encodeURIComponent(msg)}`
|
|
7993
|
+
});
|
|
7994
|
+
res.end();
|
|
7898
7995
|
}
|
|
7899
7996
|
return;
|
|
7900
7997
|
}
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
|
|
7904
|
-
|
|
7905
|
-
|
|
7906
|
-
|
|
7907
|
-
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7998
|
+
const authUrl = buildOAuth2AuthorizeUrl({
|
|
7999
|
+
clientId: nextCreds.clientId,
|
|
8000
|
+
redirectUri: activeRedirectUri,
|
|
8001
|
+
state: oauthState,
|
|
8002
|
+
codeChallenge: pkce.codeChallenge
|
|
8003
|
+
});
|
|
8004
|
+
res.writeHead(302, { Location: authUrl });
|
|
8005
|
+
res.end();
|
|
8006
|
+
return;
|
|
8007
|
+
}
|
|
8008
|
+
if (req.method === "GET" && path === callbackPath) {
|
|
8009
|
+
const oauthError = reqUrl.searchParams.get("error");
|
|
8010
|
+
const oauthErrorDesc = reqUrl.searchParams.get("error_description");
|
|
8011
|
+
if (oauthError) {
|
|
8012
|
+
const msg = `X authorization declined (${oauthError}): ${oauthErrorDesc ?? "no details"}`;
|
|
8013
|
+
sendHtml(res, 400, "X Authorization Declined", `<h1>Authorization Declined</h1><p>${escapeHtml(msg)}</p>`);
|
|
8014
|
+
finishReject(new Error(msg));
|
|
8015
|
+
return;
|
|
8016
|
+
}
|
|
8017
|
+
const code = (reqUrl.searchParams.get("code") ?? "").trim();
|
|
8018
|
+
const returnedState = (reqUrl.searchParams.get("state") ?? "").trim();
|
|
8019
|
+
if (!code || returnedState !== oauthState || !credentials) {
|
|
8020
|
+
const msg = "Invalid OAuth 2.0 callback state or missing authorization code.";
|
|
8021
|
+
sendHtml(res, 400, "Invalid OAuth 2.0 Callback", `<h1>Invalid Callback</h1><p>${escapeHtml(msg)}</p>`);
|
|
8022
|
+
finishReject(new Error(msg));
|
|
8023
|
+
return;
|
|
8024
|
+
}
|
|
8025
|
+
try {
|
|
8026
|
+
const tokenResp = await exchangeAuthorizationCode({
|
|
8027
|
+
credentials,
|
|
8028
|
+
code,
|
|
8029
|
+
redirectUri: activeRedirectUri,
|
|
8030
|
+
codeVerifier: pkce.codeVerifier
|
|
8031
|
+
});
|
|
8032
|
+
const tokenSource = saveOAuth2UserTokens(credentials.clientId, {
|
|
8033
|
+
accessToken: tokenResp.accessToken,
|
|
8034
|
+
refreshToken: tokenResp.refreshToken,
|
|
8035
|
+
expiresAt: tokenResp.expiresAt,
|
|
8036
|
+
scope: tokenResp.scope
|
|
7918
8037
|
});
|
|
7919
8038
|
sendHtml(
|
|
7920
8039
|
res,
|
|
7921
8040
|
200,
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
"<h1>Authentication Complete</h1><p>Authorization succeeded. You may close this tab and return to your agent.</p>"
|
|
7925
|
-
)
|
|
8041
|
+
"X Connected",
|
|
8042
|
+
"<h1>Authorized!</h1><p>Long-term OAuth 2.0 authorization completed. You can close this tab and return to your agent.</p>"
|
|
7926
8043
|
);
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
entryUrl
|
|
8044
|
+
finishResolve({
|
|
8045
|
+
credentials,
|
|
8046
|
+
credentialSource,
|
|
8047
|
+
tokenSource,
|
|
8048
|
+
accessToken: tokenResp.accessToken,
|
|
8049
|
+
refreshToken: tokenResp.refreshToken,
|
|
8050
|
+
expiresAt: tokenResp.expiresAt,
|
|
8051
|
+
scope: tokenResp.scope,
|
|
8052
|
+
redirectUri: activeRedirectUri
|
|
7937
8053
|
});
|
|
7938
|
-
|
|
8054
|
+
} catch (err) {
|
|
8055
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
8056
|
+
sendHtml(res, 500, "Token Exchange Failed", `<h1>Token Exchange Failed</h1><p>${escapeHtml(msg)}</p>`);
|
|
8057
|
+
finishReject(err instanceof Error ? err : new Error(msg));
|
|
7939
8058
|
}
|
|
7940
|
-
|
|
7941
|
-
res.end("Not found.");
|
|
7942
|
-
} catch (err) {
|
|
7943
|
-
clearTimeout(timer);
|
|
7944
|
-
server.close();
|
|
7945
|
-
rejectDone(err instanceof Error ? err : new Error(String(err)));
|
|
8059
|
+
return;
|
|
7946
8060
|
}
|
|
7947
|
-
|
|
7948
|
-
|
|
7949
|
-
|
|
7950
|
-
|
|
8061
|
+
res.writeHead(404);
|
|
8062
|
+
res.end("Not found");
|
|
8063
|
+
};
|
|
8064
|
+
let server = null;
|
|
8065
|
+
try {
|
|
8066
|
+
server = await new Promise((resolveServer, rejectServer) => {
|
|
8067
|
+
const s = createServer((req, res) => {
|
|
8068
|
+
handleRequest(req, res).catch((err) => {
|
|
8069
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
8070
|
+
sendHtml(res, 500, "Error", `<h1>Unexpected Error</h1><pre>${escapeHtml(msg)}</pre>`);
|
|
8071
|
+
});
|
|
8072
|
+
});
|
|
8073
|
+
s.once("error", rejectServer);
|
|
8074
|
+
s.listen(port, host, () => {
|
|
8075
|
+
s.removeListener("error", rejectServer);
|
|
8076
|
+
resolveServer(s);
|
|
8077
|
+
});
|
|
8078
|
+
});
|
|
8079
|
+
} catch (err) {
|
|
8080
|
+
const code = err?.code;
|
|
8081
|
+
if (code === "EADDRINUSE") {
|
|
8082
|
+
throw new Error(
|
|
8083
|
+
`OAuth 2.0 callback port ${host}:${port} is already in use (EADDRINUSE). Free port ${port}, set X_OAUTH_CALLBACK_PORT / X_OAUTH_REDIRECT_URI to an open port registered in https://console.x.com, or generate a Refresh Token directly in https://console.x.com and configure X_OAUTH2_REFRESH_TOKEN.`
|
|
8084
|
+
);
|
|
8085
|
+
}
|
|
8086
|
+
throw err;
|
|
8087
|
+
}
|
|
8088
|
+
boundPort = server.address().port;
|
|
8089
|
+
activeRedirectUri = explicitRedirectUri ?? `http://${host}:${boundPort}${callbackPath}`;
|
|
7951
8090
|
const timer = setTimeout(() => {
|
|
7952
|
-
|
|
7953
|
-
rejectDone(new Error("Timed out waiting for X OAuth setup/authorization in browser."));
|
|
8091
|
+
finishReject(new Error(`OAuth 2.0 login timed out after ${timeoutSec}s.`));
|
|
7954
8092
|
}, timeoutSec * 1e3);
|
|
7955
|
-
let entryUrl;
|
|
7956
8093
|
try {
|
|
7957
|
-
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
|
|
7962
|
-
|
|
8094
|
+
const entryUrl = credentials ? buildOAuth2AuthorizeUrl({
|
|
8095
|
+
clientId: credentials.clientId,
|
|
8096
|
+
redirectUri: activeRedirectUri,
|
|
8097
|
+
state: oauthState,
|
|
8098
|
+
codeChallenge: pkce.codeChallenge
|
|
8099
|
+
}) : `http://${host}:${boundPort}/setup?s=${csrfToken}`;
|
|
8100
|
+
options.onServerReady?.(entryUrl);
|
|
8101
|
+
openBrowserUrl(entryUrl);
|
|
8102
|
+
return await donePromise;
|
|
8103
|
+
} finally {
|
|
7963
8104
|
clearTimeout(timer);
|
|
7964
|
-
server
|
|
7965
|
-
throw err;
|
|
8105
|
+
server?.close();
|
|
7966
8106
|
}
|
|
7967
|
-
process.stderr.write(`[@wezzard/mcp-x-articles] Opening browser for X authentication: ${entryUrl}
|
|
7968
|
-
`);
|
|
7969
|
-
options.onServerReady?.(entryUrl);
|
|
7970
|
-
openBrowserUrl(entryUrl);
|
|
7971
|
-
return donePromise;
|
|
7972
8107
|
}
|
|
7973
8108
|
|
|
7974
8109
|
// src/server.ts
|
|
7975
|
-
import { existsSync as existsSync3, readFileSync as readFileSync6, statSync } from "node:fs";
|
|
8110
|
+
import { existsSync as existsSync3, readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
|
|
7976
8111
|
import { dirname as dirname3, resolve as resolve4 } from "node:path";
|
|
7977
8112
|
|
|
7978
8113
|
// node_modules/zod/v4/core/util.js
|
|
@@ -19258,7 +19393,7 @@ function convertMarkdownFile(markdownPath, options = {}) {
|
|
|
19258
19393
|
}
|
|
19259
19394
|
|
|
19260
19395
|
// src/preflight-token.ts
|
|
19261
|
-
import { createHash as
|
|
19396
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
19262
19397
|
import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
|
|
19263
19398
|
import { dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
19264
19399
|
|
|
@@ -19351,7 +19486,7 @@ function scanSensitiveFile(markdownPath, alsoPaths = []) {
|
|
|
19351
19486
|
|
|
19352
19487
|
// src/preflight-token.ts
|
|
19353
19488
|
function sha256Bytes(buf) {
|
|
19354
|
-
return
|
|
19489
|
+
return createHash3("sha256").update(buf).digest("hex");
|
|
19355
19490
|
}
|
|
19356
19491
|
function resolveCoverImagePath(markdownPath, explicitCoverPath, omitCover) {
|
|
19357
19492
|
if (omitCover) return void 0;
|
|
@@ -19421,6 +19556,7 @@ function verifyPreflightToken(providedToken, input) {
|
|
|
19421
19556
|
import { readFileSync as readFileSync5 } from "node:fs";
|
|
19422
19557
|
import { extname, resolve as resolve3 } from "node:path";
|
|
19423
19558
|
var CHUNK_SIZE_BYTES = 25e5;
|
|
19559
|
+
var REFRESH_BUFFER_SECONDS = 300;
|
|
19424
19560
|
function guessMediaType(pathOrUrl) {
|
|
19425
19561
|
const clean = pathOrUrl.split("?")[0].split("#")[0];
|
|
19426
19562
|
const ext = extname(clean).toLowerCase();
|
|
@@ -19439,18 +19575,66 @@ function guessMediaType(pathOrUrl) {
|
|
|
19439
19575
|
};
|
|
19440
19576
|
return mapping[ext] ?? "image/png";
|
|
19441
19577
|
}
|
|
19442
|
-
function
|
|
19443
|
-
|
|
19578
|
+
function guessMediaCategory(mediaType) {
|
|
19579
|
+
const normalized = mediaType.trim().toLowerCase();
|
|
19580
|
+
if (normalized === "image/gif") return "tweet_gif";
|
|
19581
|
+
if (normalized.startsWith("video/")) return "tweet_video";
|
|
19582
|
+
return "tweet_image";
|
|
19583
|
+
}
|
|
19584
|
+
function activeEnvRefreshSeedHash() {
|
|
19585
|
+
const raw = (process.env.X_OAUTH2_REFRESH_TOKEN ?? "").trim();
|
|
19586
|
+
if (!raw || raw.startsWith("${")) return void 0;
|
|
19587
|
+
return sha256Hex(raw);
|
|
19588
|
+
}
|
|
19589
|
+
async function refreshSessionLocked(credentials, staleTokens) {
|
|
19590
|
+
return withOAuth2RefreshLock(async () => {
|
|
19591
|
+
const latest = loadOAuth2UserTokens(credentials.clientId);
|
|
19592
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
19593
|
+
if (latest.tokens && latest.tokens.accessToken && latest.tokens.accessToken !== staleTokens.accessToken && latest.tokens.expiresAt > now + REFRESH_BUFFER_SECONDS) {
|
|
19594
|
+
return {
|
|
19595
|
+
tokens: latest.tokens,
|
|
19596
|
+
tokenSource: latest.source,
|
|
19597
|
+
refreshed: false
|
|
19598
|
+
};
|
|
19599
|
+
}
|
|
19600
|
+
const refreshTokenToUse = latest.tokens?.refreshToken ?? staleTokens.refreshToken;
|
|
19601
|
+
if (!refreshTokenToUse) {
|
|
19602
|
+
throw new OAuth2TokenError("No OAuth 2.0 refresh token is available to refresh session.", 401);
|
|
19603
|
+
}
|
|
19604
|
+
const refreshed = await refreshOAuth2Token({
|
|
19605
|
+
credentials,
|
|
19606
|
+
refreshToken: refreshTokenToUse
|
|
19607
|
+
});
|
|
19608
|
+
const nextRefreshToken = refreshed.refreshToken ?? refreshTokenToUse;
|
|
19609
|
+
const nextScope = refreshed.scope ?? latest.tokens?.scope ?? staleTokens.scope;
|
|
19610
|
+
const seedRefreshTokenHash = latest.tokens?.seedRefreshTokenHash ?? staleTokens.seedRefreshTokenHash ?? activeEnvRefreshSeedHash();
|
|
19611
|
+
const savedAt = Math.floor(Date.now() / 1e3);
|
|
19612
|
+
const savedSource = saveOAuth2UserTokens(credentials.clientId, {
|
|
19613
|
+
accessToken: refreshed.accessToken,
|
|
19614
|
+
refreshToken: nextRefreshToken,
|
|
19615
|
+
expiresAt: refreshed.expiresAt,
|
|
19616
|
+
scope: nextScope,
|
|
19617
|
+
savedAt,
|
|
19618
|
+
seedRefreshTokenHash
|
|
19619
|
+
});
|
|
19620
|
+
return {
|
|
19621
|
+
tokens: {
|
|
19622
|
+
accessToken: refreshed.accessToken,
|
|
19623
|
+
refreshToken: nextRefreshToken,
|
|
19624
|
+
expiresAt: refreshed.expiresAt,
|
|
19625
|
+
...nextScope ? { scope: nextScope } : {},
|
|
19626
|
+
savedAt,
|
|
19627
|
+
...seedRefreshTokenHash ? { seedRefreshTokenHash } : {}
|
|
19628
|
+
},
|
|
19629
|
+
tokenSource: savedSource,
|
|
19630
|
+
refreshed: true
|
|
19631
|
+
};
|
|
19632
|
+
});
|
|
19444
19633
|
}
|
|
19445
|
-
async function
|
|
19634
|
+
async function rawBearerJsonRequest(options) {
|
|
19446
19635
|
const url = `${getApiBaseUrl()}${options.pathWithQuery}`;
|
|
19447
|
-
const authHeader = signOAuth1Header({
|
|
19448
|
-
method: options.method,
|
|
19449
|
-
url,
|
|
19450
|
-
credentials: options.signingCreds
|
|
19451
|
-
});
|
|
19452
19636
|
const headers = {
|
|
19453
|
-
Authorization:
|
|
19637
|
+
Authorization: `Bearer ${options.accessToken}`,
|
|
19454
19638
|
"X-B3-Flags": (process.env.X_B3_FLAGS ?? "1").trim() || "1"
|
|
19455
19639
|
};
|
|
19456
19640
|
let bodyStr;
|
|
@@ -19477,91 +19661,222 @@ async function signedJsonRequest(options) {
|
|
|
19477
19661
|
`X API returned 402 Payment Required (${options.pathWithQuery}): your X Developer App credit balance is depleted. Top up credits at https://console.x.com. Raw response: ${text}`
|
|
19478
19662
|
);
|
|
19479
19663
|
}
|
|
19480
|
-
return { status: resp.status, data: parsed };
|
|
19664
|
+
return { status: resp.status, data: parsed, rawText: text };
|
|
19665
|
+
}
|
|
19666
|
+
async function authorizedJsonRequest(options) {
|
|
19667
|
+
const first = await rawBearerJsonRequest({
|
|
19668
|
+
method: options.method,
|
|
19669
|
+
pathWithQuery: options.pathWithQuery,
|
|
19670
|
+
accessToken: options.session.accessToken,
|
|
19671
|
+
jsonBody: options.jsonBody
|
|
19672
|
+
});
|
|
19673
|
+
if (first.status !== 401 || !options.session.refreshToken) {
|
|
19674
|
+
return first;
|
|
19675
|
+
}
|
|
19676
|
+
const rotated = await refreshSessionLocked(options.session.credentials, {
|
|
19677
|
+
accessToken: options.session.accessToken,
|
|
19678
|
+
refreshToken: options.session.refreshToken,
|
|
19679
|
+
expiresAt: options.session.expiresAt,
|
|
19680
|
+
scope: options.session.scope,
|
|
19681
|
+
savedAt: Math.floor(Date.now() / 1e3),
|
|
19682
|
+
seedRefreshTokenHash: options.session.seedRefreshTokenHash
|
|
19683
|
+
});
|
|
19684
|
+
options.session.accessToken = rotated.tokens.accessToken;
|
|
19685
|
+
options.session.refreshToken = rotated.tokens.refreshToken;
|
|
19686
|
+
options.session.expiresAt = rotated.tokens.expiresAt;
|
|
19687
|
+
options.session.scope = rotated.tokens.scope;
|
|
19688
|
+
options.session.tokenSource = rotated.tokenSource;
|
|
19689
|
+
options.session.seedRefreshTokenHash = rotated.tokens.seedRefreshTokenHash;
|
|
19690
|
+
options.session.refreshed = options.session.refreshed || rotated.refreshed;
|
|
19691
|
+
return rawBearerJsonRequest({
|
|
19692
|
+
method: options.method,
|
|
19693
|
+
pathWithQuery: options.pathWithQuery,
|
|
19694
|
+
accessToken: options.session.accessToken,
|
|
19695
|
+
jsonBody: options.jsonBody
|
|
19696
|
+
});
|
|
19697
|
+
}
|
|
19698
|
+
function buildMissingTokenHint(credentialSource, reason) {
|
|
19699
|
+
const hostUi = detectHostConfigUi();
|
|
19700
|
+
const prefix = reason ? `${reason} ` : "";
|
|
19701
|
+
if (hostUi.hasNativeConfigUi) {
|
|
19702
|
+
const uiRef = hostUi.configUiUrl ? `[X Articles](${hostUi.configUiUrl})` : "your host's MCP plugin configuration UI";
|
|
19703
|
+
return `${prefix}Client ID found (${credentialSource}), but no valid OAuth 2.0 user token is configured yet. Either click Generate next to OAuth 2.0 Keys -> Access Token in https://console.x.com and paste the Refresh Token into X_OAUTH2_REFRESH_TOKEN in ${uiRef}, or call \`x_article_auth_status({ login: true })\` to authorize your account on x.com in your browser (requires callback URI \`http://127.0.0.1:8976/oauth/callback\` in console.x.com).`;
|
|
19704
|
+
}
|
|
19705
|
+
return `${prefix}No cached OAuth 2.0 user token found. Call \`x_article_auth_status({ login: true })\` or run \`npx @wezzard/mcp-x-articles auth\` to authorize in your browser.`;
|
|
19481
19706
|
}
|
|
19482
19707
|
async function ensureAuthenticatedSession(options) {
|
|
19483
|
-
|
|
19484
|
-
let
|
|
19485
|
-
let
|
|
19486
|
-
|
|
19487
|
-
|
|
19488
|
-
|
|
19489
|
-
|
|
19490
|
-
|
|
19491
|
-
tokenSecret: tokens.accessSecret
|
|
19492
|
-
};
|
|
19493
|
-
const probe = await signedJsonRequest({
|
|
19494
|
-
method: "GET",
|
|
19495
|
-
pathWithQuery: "/2/users/me",
|
|
19496
|
-
signingCreds: signingCreds2
|
|
19497
|
-
});
|
|
19498
|
-
if (probe.status !== 401) {
|
|
19499
|
-
return {
|
|
19500
|
-
signingCreds: signingCreds2,
|
|
19501
|
-
credentialSource,
|
|
19502
|
-
tokenSource,
|
|
19503
|
-
user: probe.data?.data
|
|
19504
|
-
};
|
|
19708
|
+
const hostUi = detectHostConfigUi();
|
|
19709
|
+
let { credentials, source: credentialSource } = loadOAuth2ClientCredentials();
|
|
19710
|
+
let tokens = null;
|
|
19711
|
+
let tokenSource = "none";
|
|
19712
|
+
let refreshedFlag = false;
|
|
19713
|
+
if (!credentials) {
|
|
19714
|
+
if (hostUi.hasNativeConfigUi || !options.allowInteractiveLogin) {
|
|
19715
|
+
throw new Error(`Missing X OAuth 2.0 Client ID. ${hostUi.setupInstruction}`);
|
|
19505
19716
|
}
|
|
19506
|
-
|
|
19507
|
-
|
|
19508
|
-
|
|
19509
|
-
}
|
|
19510
|
-
|
|
19717
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
19718
|
+
existingCredentials: null,
|
|
19719
|
+
existingCredentialSource: "none"
|
|
19720
|
+
});
|
|
19721
|
+
credentials = interactive.credentials;
|
|
19722
|
+
credentialSource = interactive.credentialSource;
|
|
19723
|
+
tokenSource = interactive.tokenSource;
|
|
19724
|
+
tokens = {
|
|
19725
|
+
accessToken: interactive.accessToken,
|
|
19726
|
+
refreshToken: interactive.refreshToken,
|
|
19727
|
+
expiresAt: interactive.expiresAt,
|
|
19728
|
+
scope: interactive.scope,
|
|
19729
|
+
savedAt: Math.floor(Date.now() / 1e3),
|
|
19730
|
+
seedRefreshTokenHash: interactive.seedRefreshTokenHash
|
|
19731
|
+
};
|
|
19732
|
+
} else {
|
|
19733
|
+
const loaded = loadOAuth2UserTokens(credentials.clientId);
|
|
19734
|
+
tokens = loaded.tokens;
|
|
19735
|
+
tokenSource = loaded.source;
|
|
19736
|
+
}
|
|
19737
|
+
if (tokens) {
|
|
19738
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
19739
|
+
const needsProactiveRefresh = !tokens.accessToken || now >= tokens.expiresAt - REFRESH_BUFFER_SECONDS;
|
|
19740
|
+
if (needsProactiveRefresh) {
|
|
19741
|
+
if (tokens.refreshToken) {
|
|
19742
|
+
try {
|
|
19743
|
+
const rotated = await refreshSessionLocked(credentials, tokens);
|
|
19744
|
+
tokens = rotated.tokens;
|
|
19745
|
+
tokenSource = rotated.tokenSource;
|
|
19746
|
+
refreshedFlag = rotated.refreshed;
|
|
19747
|
+
} catch (err) {
|
|
19748
|
+
const isInvalidGrant = err instanceof OAuth2TokenError && (err.oauthError === "invalid_grant" || err.status === 400 || err.status === 401);
|
|
19749
|
+
if (!isInvalidGrant) {
|
|
19750
|
+
throw err;
|
|
19751
|
+
}
|
|
19752
|
+
if (tokenSource !== "env") {
|
|
19753
|
+
clearOAuth2UserTokens(credentials.clientId);
|
|
19754
|
+
}
|
|
19755
|
+
tokens = null;
|
|
19756
|
+
if (!options.allowInteractiveLogin) {
|
|
19757
|
+
throw new Error(buildMissingTokenHint(credentialSource, err.message));
|
|
19758
|
+
}
|
|
19759
|
+
}
|
|
19760
|
+
} else if (!tokens.accessToken) {
|
|
19761
|
+
if (tokenSource !== "env") {
|
|
19762
|
+
clearOAuth2UserTokens(credentials.clientId);
|
|
19763
|
+
}
|
|
19764
|
+
tokens = null;
|
|
19765
|
+
}
|
|
19511
19766
|
}
|
|
19512
19767
|
}
|
|
19513
|
-
if (!
|
|
19768
|
+
if (!tokens) {
|
|
19514
19769
|
if (!options.allowInteractiveLogin) {
|
|
19515
|
-
|
|
19516
|
-
throw new Error(
|
|
19517
|
-
"Missing X OAuth Consumer Key and Secret. Call `x_article_auth_status({ login: true })` to open the local browser Keychain setup page, or run `npx @wezzard/mcp-x-articles auth`."
|
|
19518
|
-
);
|
|
19519
|
-
}
|
|
19520
|
-
throw new Error(
|
|
19521
|
-
"No cached OAuth 1.0a user token found. Call `x_article_auth_status({ login: true })` or run `npx @wezzard/mcp-x-articles auth` to authorize in your browser."
|
|
19522
|
-
);
|
|
19770
|
+
throw new Error(buildMissingTokenHint(credentialSource));
|
|
19523
19771
|
}
|
|
19524
|
-
const interactive = await
|
|
19772
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
19525
19773
|
existingCredentials: credentials,
|
|
19526
19774
|
existingCredentialSource: credentialSource
|
|
19527
19775
|
});
|
|
19528
19776
|
credentials = interactive.credentials;
|
|
19529
19777
|
credentialSource = interactive.credentialSource;
|
|
19530
|
-
|
|
19531
|
-
|
|
19532
|
-
|
|
19533
|
-
|
|
19534
|
-
|
|
19778
|
+
const seedHash = interactive.seedRefreshTokenHash ?? activeEnvRefreshSeedHash();
|
|
19779
|
+
if (seedHash && !interactive.seedRefreshTokenHash) {
|
|
19780
|
+
tokenSource = saveOAuth2UserTokens(credentials.clientId, {
|
|
19781
|
+
accessToken: interactive.accessToken,
|
|
19782
|
+
refreshToken: interactive.refreshToken,
|
|
19783
|
+
expiresAt: interactive.expiresAt,
|
|
19784
|
+
scope: interactive.scope,
|
|
19785
|
+
seedRefreshTokenHash: seedHash
|
|
19786
|
+
});
|
|
19787
|
+
} else {
|
|
19788
|
+
tokenSource = interactive.tokenSource;
|
|
19789
|
+
}
|
|
19535
19790
|
tokens = {
|
|
19536
19791
|
accessToken: interactive.accessToken,
|
|
19537
|
-
|
|
19538
|
-
|
|
19792
|
+
refreshToken: interactive.refreshToken,
|
|
19793
|
+
expiresAt: interactive.expiresAt,
|
|
19794
|
+
scope: interactive.scope,
|
|
19795
|
+
savedAt: Math.floor(Date.now() / 1e3),
|
|
19796
|
+
...seedHash ? { seedRefreshTokenHash: seedHash } : {}
|
|
19539
19797
|
};
|
|
19540
19798
|
}
|
|
19541
|
-
const
|
|
19542
|
-
|
|
19543
|
-
|
|
19544
|
-
|
|
19545
|
-
|
|
19799
|
+
const session = {
|
|
19800
|
+
credentials,
|
|
19801
|
+
accessToken: tokens.accessToken,
|
|
19802
|
+
refreshToken: tokens.refreshToken,
|
|
19803
|
+
expiresAt: tokens.expiresAt,
|
|
19804
|
+
scope: tokens.scope,
|
|
19805
|
+
credentialSource,
|
|
19806
|
+
tokenSource,
|
|
19807
|
+
refreshed: refreshedFlag,
|
|
19808
|
+
seedRefreshTokenHash: tokens.seedRefreshTokenHash
|
|
19546
19809
|
};
|
|
19547
|
-
let user;
|
|
19548
19810
|
if (options.verifyProbe) {
|
|
19549
|
-
|
|
19550
|
-
|
|
19551
|
-
|
|
19552
|
-
|
|
19553
|
-
|
|
19811
|
+
let probe;
|
|
19812
|
+
try {
|
|
19813
|
+
probe = await authorizedJsonRequest({
|
|
19814
|
+
method: "GET",
|
|
19815
|
+
pathWithQuery: "/2/users/me",
|
|
19816
|
+
session
|
|
19817
|
+
});
|
|
19818
|
+
} catch (err) {
|
|
19819
|
+
const isInvalidGrant = err instanceof OAuth2TokenError && (err.oauthError === "invalid_grant" || err.status === 400 || err.status === 401);
|
|
19820
|
+
if (!isInvalidGrant || !options.allowInteractiveLogin) {
|
|
19821
|
+
throw err;
|
|
19822
|
+
}
|
|
19823
|
+
clearOAuth2UserTokens(credentials.clientId);
|
|
19824
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
19825
|
+
existingCredentials: credentials,
|
|
19826
|
+
existingCredentialSource: credentialSource
|
|
19827
|
+
});
|
|
19828
|
+
const seedHash = interactive.seedRefreshTokenHash ?? activeEnvRefreshSeedHash();
|
|
19829
|
+
session.accessToken = interactive.accessToken;
|
|
19830
|
+
session.refreshToken = interactive.refreshToken;
|
|
19831
|
+
session.expiresAt = interactive.expiresAt;
|
|
19832
|
+
session.scope = interactive.scope;
|
|
19833
|
+
session.tokenSource = seedHash ? saveOAuth2UserTokens(credentials.clientId, {
|
|
19834
|
+
accessToken: interactive.accessToken,
|
|
19835
|
+
refreshToken: interactive.refreshToken,
|
|
19836
|
+
expiresAt: interactive.expiresAt,
|
|
19837
|
+
scope: interactive.scope,
|
|
19838
|
+
seedRefreshTokenHash: seedHash
|
|
19839
|
+
}) : interactive.tokenSource;
|
|
19840
|
+
session.seedRefreshTokenHash = seedHash;
|
|
19841
|
+
probe = await rawBearerJsonRequest({
|
|
19842
|
+
method: "GET",
|
|
19843
|
+
pathWithQuery: "/2/users/me",
|
|
19844
|
+
accessToken: session.accessToken
|
|
19845
|
+
});
|
|
19846
|
+
}
|
|
19847
|
+
if (probe.status === 401 && options.allowInteractiveLogin) {
|
|
19848
|
+
clearOAuth2UserTokens(credentials.clientId);
|
|
19849
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
19850
|
+
existingCredentials: credentials,
|
|
19851
|
+
existingCredentialSource: credentialSource
|
|
19852
|
+
});
|
|
19853
|
+
const seedHash = interactive.seedRefreshTokenHash ?? activeEnvRefreshSeedHash();
|
|
19854
|
+
session.accessToken = interactive.accessToken;
|
|
19855
|
+
session.refreshToken = interactive.refreshToken;
|
|
19856
|
+
session.expiresAt = interactive.expiresAt;
|
|
19857
|
+
session.scope = interactive.scope;
|
|
19858
|
+
session.tokenSource = seedHash ? saveOAuth2UserTokens(credentials.clientId, {
|
|
19859
|
+
accessToken: interactive.accessToken,
|
|
19860
|
+
refreshToken: interactive.refreshToken,
|
|
19861
|
+
expiresAt: interactive.expiresAt,
|
|
19862
|
+
scope: interactive.scope,
|
|
19863
|
+
seedRefreshTokenHash: seedHash
|
|
19864
|
+
}) : interactive.tokenSource;
|
|
19865
|
+
session.seedRefreshTokenHash = seedHash;
|
|
19866
|
+
probe = await rawBearerJsonRequest({
|
|
19867
|
+
method: "GET",
|
|
19868
|
+
pathWithQuery: "/2/users/me",
|
|
19869
|
+
accessToken: session.accessToken
|
|
19870
|
+
});
|
|
19871
|
+
}
|
|
19554
19872
|
if (probe.status >= 400) {
|
|
19555
|
-
throw new Error(
|
|
19873
|
+
throw new Error(
|
|
19874
|
+
`X API user verification failed (HTTP ${probe.status}): ${JSON.stringify(probe.data)}`
|
|
19875
|
+
);
|
|
19556
19876
|
}
|
|
19557
|
-
user = probe.data?.data;
|
|
19877
|
+
session.user = probe.data?.data;
|
|
19558
19878
|
}
|
|
19559
|
-
return
|
|
19560
|
-
signingCreds,
|
|
19561
|
-
credentialSource,
|
|
19562
|
-
tokenSource,
|
|
19563
|
-
user
|
|
19564
|
-
};
|
|
19879
|
+
return session;
|
|
19565
19880
|
}
|
|
19566
19881
|
async function loadImageBytes(pathOrUrl) {
|
|
19567
19882
|
if (isRemoteUrl(pathOrUrl)) {
|
|
@@ -19585,11 +19900,11 @@ async function loadImageBytes(pathOrUrl) {
|
|
|
19585
19900
|
};
|
|
19586
19901
|
}
|
|
19587
19902
|
async function uploadMediaBuffer(options) {
|
|
19588
|
-
const mediaCategory = options.mediaCategory ??
|
|
19589
|
-
const initResp = await
|
|
19903
|
+
const mediaCategory = options.mediaCategory ?? guessMediaCategory(options.mediaType);
|
|
19904
|
+
const initResp = await authorizedJsonRequest({
|
|
19590
19905
|
method: "POST",
|
|
19591
19906
|
pathWithQuery: "/2/media/upload/initialize",
|
|
19592
|
-
|
|
19907
|
+
session: options.session,
|
|
19593
19908
|
jsonBody: {
|
|
19594
19909
|
media_category: mediaCategory,
|
|
19595
19910
|
media_type: options.mediaType,
|
|
@@ -19608,10 +19923,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19608
19923
|
let segmentIndex = 0;
|
|
19609
19924
|
for (let offset = 0; offset < options.bytes.length; offset += CHUNK_SIZE_BYTES) {
|
|
19610
19925
|
const chunk = options.bytes.subarray(offset, offset + CHUNK_SIZE_BYTES);
|
|
19611
|
-
const appendResp = await
|
|
19926
|
+
const appendResp = await authorizedJsonRequest({
|
|
19612
19927
|
method: "POST",
|
|
19613
19928
|
pathWithQuery: `/2/media/upload/${encodeURIComponent(mediaId)}/append`,
|
|
19614
|
-
|
|
19929
|
+
session: options.session,
|
|
19615
19930
|
jsonBody: {
|
|
19616
19931
|
media: chunk.toString("base64"),
|
|
19617
19932
|
segment_index: segmentIndex
|
|
@@ -19624,10 +19939,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19624
19939
|
}
|
|
19625
19940
|
segmentIndex += 1;
|
|
19626
19941
|
}
|
|
19627
|
-
const finResp = await
|
|
19942
|
+
const finResp = await authorizedJsonRequest({
|
|
19628
19943
|
method: "POST",
|
|
19629
19944
|
pathWithQuery: `/2/media/upload/${encodeURIComponent(mediaId)}/finalize`,
|
|
19630
|
-
|
|
19945
|
+
session: options.session
|
|
19631
19946
|
});
|
|
19632
19947
|
if (finResp.status >= 400) {
|
|
19633
19948
|
throw new Error(
|
|
@@ -19638,10 +19953,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19638
19953
|
while (proc && (proc.state === "pending" || proc.state === "in_progress")) {
|
|
19639
19954
|
const waitSeconds = Math.max(1, Number(proc.check_after_secs ?? 2));
|
|
19640
19955
|
await new Promise((r) => setTimeout(r, waitSeconds * 1e3));
|
|
19641
|
-
const statusResp = await
|
|
19956
|
+
const statusResp = await authorizedJsonRequest({
|
|
19642
19957
|
method: "GET",
|
|
19643
19958
|
pathWithQuery: `/2/media/upload?media_id=${encodeURIComponent(mediaId)}&command=STATUS`,
|
|
19644
|
-
|
|
19959
|
+
session: options.session
|
|
19645
19960
|
});
|
|
19646
19961
|
if (statusResp.status >= 400) {
|
|
19647
19962
|
throw new Error(
|
|
@@ -19670,10 +19985,10 @@ async function createXArticleDraft(options) {
|
|
|
19670
19985
|
media_id: options.coverMediaId
|
|
19671
19986
|
};
|
|
19672
19987
|
}
|
|
19673
|
-
const resp = await
|
|
19988
|
+
const resp = await authorizedJsonRequest({
|
|
19674
19989
|
method: "POST",
|
|
19675
19990
|
pathWithQuery: "/2/articles/draft",
|
|
19676
|
-
|
|
19991
|
+
session: options.session,
|
|
19677
19992
|
jsonBody: payload
|
|
19678
19993
|
});
|
|
19679
19994
|
if (resp.status >= 400) {
|
|
@@ -19694,10 +20009,10 @@ async function publishXArticle(options) {
|
|
|
19694
20009
|
if (!/^[0-9]{1,19}$/.test(cleanId)) {
|
|
19695
20010
|
throw new Error(`Invalid article_id "${options.articleId}": expected a numeric X snowflake ID.`);
|
|
19696
20011
|
}
|
|
19697
|
-
const resp = await
|
|
20012
|
+
const resp = await authorizedJsonRequest({
|
|
19698
20013
|
method: "POST",
|
|
19699
20014
|
pathWithQuery: `/2/articles/${encodeURIComponent(cleanId)}/publish`,
|
|
19700
|
-
|
|
20015
|
+
session: options.session
|
|
19701
20016
|
});
|
|
19702
20017
|
if (resp.status >= 400) {
|
|
19703
20018
|
throw new Error(`articlePublish failed (HTTP ${resp.status}): ${JSON.stringify(resp.data)}`);
|
|
@@ -19715,7 +20030,7 @@ async function publishXArticle(options) {
|
|
|
19715
20030
|
|
|
19716
20031
|
// src/server.ts
|
|
19717
20032
|
var PACKAGE_NAME = "@wezzard/mcp-x-articles";
|
|
19718
|
-
var PACKAGE_VERSION = "0.
|
|
20033
|
+
var PACKAGE_VERSION = "0.3.0";
|
|
19719
20034
|
var MAX_INLINE_PREVIEW_BYTES = 5 * 1024 * 1024;
|
|
19720
20035
|
var PREVIEWABLE_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
19721
20036
|
var SERVER_INSTRUCTIONS = [
|
|
@@ -19730,13 +20045,13 @@ var TOOLS = [
|
|
|
19730
20045
|
{
|
|
19731
20046
|
name: "x_article_auth_status",
|
|
19732
20047
|
title: "Check or Setup X Articles Authentication",
|
|
19733
|
-
description: "Check X OAuth
|
|
20048
|
+
description: "Check X OAuth 2.0 client credential resolution (Environment Variables -> macOS Keychain -> 0600 XDG config), proactively refresh rotating offline.access tokens, and verify user token validity (`GET /2/users/me`). Set `login: true` to launch localhost OAuth 2.0 PKCE browser consent when no valid user token is available.",
|
|
19734
20049
|
inputSchema: {
|
|
19735
20050
|
type: "object",
|
|
19736
20051
|
properties: {
|
|
19737
20052
|
login: {
|
|
19738
20053
|
type: "boolean",
|
|
19739
|
-
description: "When true, launches the localhost OAuth
|
|
20054
|
+
description: "When true, launches the localhost OAuth 2.0 PKCE browser consent flow if no valid user token is cached."
|
|
19740
20055
|
},
|
|
19741
20056
|
verify: {
|
|
19742
20057
|
type: "boolean",
|
|
@@ -19936,24 +20251,41 @@ function createMcpServer() {
|
|
|
19936
20251
|
if (name === "x_article_auth_status") {
|
|
19937
20252
|
const login = Boolean(args.login);
|
|
19938
20253
|
const verify = args.verify !== false;
|
|
19939
|
-
const
|
|
19940
|
-
|
|
19941
|
-
|
|
19942
|
-
|
|
19943
|
-
|
|
19944
|
-
|
|
19945
|
-
|
|
19946
|
-
|
|
20254
|
+
const hostUi = detectHostConfigUi();
|
|
20255
|
+
const { credentials, source: credentialSource } = loadOAuth2ClientCredentials();
|
|
20256
|
+
if (!credentials) {
|
|
20257
|
+
if (hostUi.hasNativeConfigUi || !login) {
|
|
20258
|
+
return jsonToolResult({
|
|
20259
|
+
auth_mode: "oauth2",
|
|
20260
|
+
configured: false,
|
|
20261
|
+
credential_source: "none",
|
|
20262
|
+
token_cached: false,
|
|
20263
|
+
has_refresh_token: false,
|
|
20264
|
+
access_token_expires_at: null,
|
|
20265
|
+
scopes: null,
|
|
20266
|
+
refreshed: false,
|
|
20267
|
+
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
20268
|
+
native_config_ui_url: hostUi.configUiUrl,
|
|
20269
|
+
setup_hint: hostUi.setupInstruction
|
|
20270
|
+
});
|
|
20271
|
+
}
|
|
19947
20272
|
}
|
|
19948
20273
|
if (credentials) {
|
|
19949
|
-
const cached2 =
|
|
20274
|
+
const cached2 = loadOAuth2UserTokens(credentials.clientId);
|
|
19950
20275
|
if (!cached2.tokens && !login) {
|
|
19951
20276
|
return jsonToolResult({
|
|
20277
|
+
auth_mode: "oauth2",
|
|
19952
20278
|
configured: true,
|
|
19953
20279
|
credential_source: credentialSource,
|
|
19954
20280
|
token_cached: false,
|
|
19955
20281
|
token_source: "none",
|
|
19956
|
-
|
|
20282
|
+
has_refresh_token: false,
|
|
20283
|
+
access_token_expires_at: null,
|
|
20284
|
+
scopes: null,
|
|
20285
|
+
refreshed: false,
|
|
20286
|
+
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
20287
|
+
native_config_ui_url: hostUi.configUiUrl,
|
|
20288
|
+
setup_hint: hostUi.hasNativeConfigUi ? `OAuth 2.0 Client ID found (${credentialSource}), but no user Refresh Token or Access Token is configured yet. Either click Generate next to OAuth 2.0 Keys -> Access Token in https://console.x.com and paste the Refresh Token into X_OAUTH2_REFRESH_TOKEN in ${hostUi.configUiUrl ? `[X Articles](${hostUi.configUiUrl})` : "your host's MCP plugin configuration UI"}, or call \`x_article_auth_status({ login: true })\` to authorize your account on x.com in your browser.` : "OAuth 2.0 Client ID found, but no user OAuth 2.0 token is cached yet. Call `x_article_auth_status({ login: true })` to authorize in your browser."
|
|
19957
20289
|
});
|
|
19958
20290
|
}
|
|
19959
20291
|
}
|
|
@@ -19962,10 +20294,17 @@ function createMcpServer() {
|
|
|
19962
20294
|
verifyProbe: verify
|
|
19963
20295
|
});
|
|
19964
20296
|
return jsonToolResult({
|
|
20297
|
+
auth_mode: "oauth2",
|
|
19965
20298
|
configured: true,
|
|
19966
20299
|
credential_source: session.credentialSource,
|
|
19967
20300
|
token_cached: true,
|
|
19968
20301
|
token_source: session.tokenSource,
|
|
20302
|
+
has_refresh_token: Boolean(session.refreshToken),
|
|
20303
|
+
access_token_expires_at: session.expiresAt ? new Date(session.expiresAt * 1e3).toISOString() : null,
|
|
20304
|
+
scopes: session.scope ?? null,
|
|
20305
|
+
refreshed: Boolean(session.refreshed),
|
|
20306
|
+
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
20307
|
+
native_config_ui_url: hostUi.configUiUrl,
|
|
19969
20308
|
verified: verify,
|
|
19970
20309
|
authenticated_user: session.user ?? null
|
|
19971
20310
|
});
|
|
@@ -20025,7 +20364,7 @@ function createMcpServer() {
|
|
|
20025
20364
|
if (includePreviews) {
|
|
20026
20365
|
for (const img of reviewImagePaths) {
|
|
20027
20366
|
if (img.is_remote || !existsSync3(img.resolved_path)) continue;
|
|
20028
|
-
const st2 =
|
|
20367
|
+
const st2 = statSync2(img.resolved_path);
|
|
20029
20368
|
if (!st2.isFile() || st2.size > MAX_INLINE_PREVIEW_BYTES) continue;
|
|
20030
20369
|
const mime = guessMediaType(img.resolved_path);
|
|
20031
20370
|
if (!PREVIEWABLE_MIMES.has(mime)) continue;
|
|
@@ -20090,8 +20429,8 @@ function createMcpServer() {
|
|
|
20090
20429
|
const up = await uploadMediaBuffer({
|
|
20091
20430
|
bytes: loaded.bytes,
|
|
20092
20431
|
mediaType: loaded.mediaType,
|
|
20093
|
-
mediaCategory:
|
|
20094
|
-
|
|
20432
|
+
mediaCategory: guessMediaCategory(loaded.mediaType),
|
|
20433
|
+
session,
|
|
20095
20434
|
label: src
|
|
20096
20435
|
});
|
|
20097
20436
|
mediaMap[src] = {
|
|
@@ -20111,7 +20450,7 @@ function createMcpServer() {
|
|
|
20111
20450
|
bytes: loadedCover.bytes,
|
|
20112
20451
|
mediaType: loadedCover.mediaType,
|
|
20113
20452
|
mediaCategory: "tweet_image",
|
|
20114
|
-
|
|
20453
|
+
session,
|
|
20115
20454
|
label: "cover_image"
|
|
20116
20455
|
});
|
|
20117
20456
|
coverMediaId = upCover.media_id;
|
|
@@ -20125,7 +20464,7 @@ function createMcpServer() {
|
|
|
20125
20464
|
contentState: finalConversion.content_state,
|
|
20126
20465
|
coverMediaId,
|
|
20127
20466
|
coverMediaCategory: "tweet_image",
|
|
20128
|
-
|
|
20467
|
+
session
|
|
20129
20468
|
});
|
|
20130
20469
|
return jsonToolResult({
|
|
20131
20470
|
ok: true,
|
|
@@ -20149,7 +20488,7 @@ function createMcpServer() {
|
|
|
20149
20488
|
});
|
|
20150
20489
|
const published = await publishXArticle({
|
|
20151
20490
|
articleId,
|
|
20152
|
-
|
|
20491
|
+
session,
|
|
20153
20492
|
usernameHint: session.user?.username
|
|
20154
20493
|
});
|
|
20155
20494
|
return jsonToolResult({
|
|
@@ -20185,8 +20524,8 @@ function printHelp() {
|
|
|
20185
20524
|
"",
|
|
20186
20525
|
"Usage:",
|
|
20187
20526
|
" mcp-x-articles Start the MCP server over stdio (default)",
|
|
20188
|
-
" mcp-x-articles auth Configure X OAuth
|
|
20189
|
-
" mcp-x-articles status Show current credential and
|
|
20527
|
+
" mcp-x-articles auth Configure X OAuth 2.0 keys in macOS Keychain and authorize in browser",
|
|
20528
|
+
" mcp-x-articles status Show current OAuth 2.0 credential and token status",
|
|
20190
20529
|
" mcp-x-articles --version Print package version",
|
|
20191
20530
|
" mcp-x-articles --help Print this help message",
|
|
20192
20531
|
""
|
|
@@ -20194,57 +20533,80 @@ function printHelp() {
|
|
|
20194
20533
|
);
|
|
20195
20534
|
}
|
|
20196
20535
|
async function runAuthCli(resetKeys) {
|
|
20197
|
-
let { credentials, source } =
|
|
20536
|
+
let { credentials, source } = loadOAuth2ClientCredentials();
|
|
20537
|
+
let cliRefreshToken = "";
|
|
20198
20538
|
if (!credentials || resetKeys) {
|
|
20199
20539
|
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
20200
20540
|
try {
|
|
20201
20541
|
process.stderr.write(
|
|
20202
|
-
"
|
|
20542
|
+
"For browser PKCE login, register http://127.0.0.1:8976/oauth/callback in https://console.x.com.\nOr click Generate next to OAuth 2.0 Keys -> Access Token in https://console.x.com and paste the Refresh Token below.\n\n"
|
|
20203
20543
|
);
|
|
20204
|
-
const
|
|
20205
|
-
const
|
|
20206
|
-
|
|
20207
|
-
|
|
20208
|
-
|
|
20209
|
-
|
|
20210
|
-
|
|
20211
|
-
|
|
20544
|
+
const clientId = (await rl.question("X OAuth 2.0 Client ID: ")).trim();
|
|
20545
|
+
const clientSecret = (await rl.question("X OAuth 2.0 Client Secret (optional for public clients): ")).trim() || void 0;
|
|
20546
|
+
cliRefreshToken = (await rl.question("X OAuth 2.0 Refresh Token (leave blank for browser PKCE login): ")).trim();
|
|
20547
|
+
if (!clientId) {
|
|
20548
|
+
throw new Error("X OAuth 2.0 Client ID is required.");
|
|
20549
|
+
}
|
|
20550
|
+
source = saveOAuth2ClientCredentials({
|
|
20551
|
+
clientId,
|
|
20552
|
+
...clientSecret ? { clientSecret } : {}
|
|
20553
|
+
});
|
|
20554
|
+
credentials = {
|
|
20555
|
+
clientId,
|
|
20556
|
+
...clientSecret ? { clientSecret } : {}
|
|
20557
|
+
};
|
|
20558
|
+
process.stderr.write(`Saved OAuth 2.0 client credentials to ${source}.
|
|
20212
20559
|
`);
|
|
20213
20560
|
} finally {
|
|
20214
20561
|
rl.close();
|
|
20215
20562
|
}
|
|
20216
20563
|
} else {
|
|
20217
|
-
process.stderr.write(`Using existing
|
|
20564
|
+
process.stderr.write(`Using existing OAuth 2.0 client credentials from ${source}.
|
|
20218
20565
|
`);
|
|
20219
20566
|
}
|
|
20220
|
-
|
|
20221
|
-
|
|
20222
|
-
|
|
20223
|
-
|
|
20224
|
-
|
|
20225
|
-
|
|
20226
|
-
|
|
20227
|
-
|
|
20228
|
-
|
|
20567
|
+
let tokenStore = source;
|
|
20568
|
+
if (cliRefreshToken) {
|
|
20569
|
+
const refreshed = await refreshOAuth2Token({
|
|
20570
|
+
credentials,
|
|
20571
|
+
refreshToken: cliRefreshToken
|
|
20572
|
+
});
|
|
20573
|
+
tokenStore = saveOAuth2UserTokens(credentials.clientId, {
|
|
20574
|
+
accessToken: refreshed.accessToken,
|
|
20575
|
+
refreshToken: refreshed.refreshToken ?? cliRefreshToken,
|
|
20576
|
+
expiresAt: refreshed.expiresAt,
|
|
20577
|
+
scope: refreshed.scope,
|
|
20578
|
+
seedRefreshTokenHash: sha256Hex(cliRefreshToken)
|
|
20579
|
+
});
|
|
20580
|
+
} else {
|
|
20581
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
20582
|
+
existingCredentials: credentials,
|
|
20583
|
+
existingCredentialSource: source
|
|
20584
|
+
});
|
|
20585
|
+
tokenStore = interactive.tokenSource;
|
|
20586
|
+
}
|
|
20229
20587
|
const verified = await ensureAuthenticatedSession({
|
|
20230
20588
|
allowInteractiveLogin: false,
|
|
20231
20589
|
verifyProbe: true
|
|
20232
20590
|
});
|
|
20233
20591
|
const handle = verified.user?.username ? `@${verified.user.username}` : "authenticated account";
|
|
20234
20592
|
process.stdout.write(
|
|
20235
|
-
`Authenticated ${handle} successfully (credentials: ${verified.credentialSource}, user token: ${tokenStore}).
|
|
20593
|
+
`Authenticated ${handle} via OAuth 2.0 successfully (credentials: ${verified.credentialSource}, user token: ${tokenStore}, refresh_token: ${Boolean(verified.refreshToken)}).
|
|
20236
20594
|
`
|
|
20237
20595
|
);
|
|
20238
20596
|
}
|
|
20239
20597
|
async function runStatusCli() {
|
|
20240
|
-
const { credentials, source } =
|
|
20598
|
+
const { credentials, source } = loadOAuth2ClientCredentials();
|
|
20241
20599
|
if (!credentials) {
|
|
20242
20600
|
process.stdout.write(
|
|
20243
20601
|
JSON.stringify(
|
|
20244
20602
|
{
|
|
20603
|
+
auth_mode: "oauth2",
|
|
20245
20604
|
configured: false,
|
|
20246
20605
|
credential_source: "none",
|
|
20247
20606
|
token_cached: false,
|
|
20607
|
+
has_refresh_token: false,
|
|
20608
|
+
access_token_expires_at: null,
|
|
20609
|
+
scopes: null,
|
|
20248
20610
|
hint: "Call x_article_auth_status({ login: true }) in your agent or run `npx @wezzard/mcp-x-articles auth`."
|
|
20249
20611
|
},
|
|
20250
20612
|
null,
|
|
@@ -20253,14 +20615,18 @@ async function runStatusCli() {
|
|
|
20253
20615
|
);
|
|
20254
20616
|
return;
|
|
20255
20617
|
}
|
|
20256
|
-
const tok =
|
|
20618
|
+
const tok = loadOAuth2UserTokens(credentials.clientId);
|
|
20257
20619
|
process.stdout.write(
|
|
20258
20620
|
JSON.stringify(
|
|
20259
20621
|
{
|
|
20622
|
+
auth_mode: "oauth2",
|
|
20260
20623
|
configured: true,
|
|
20261
20624
|
credential_source: source,
|
|
20262
20625
|
token_cached: Boolean(tok.tokens),
|
|
20263
|
-
token_source: tok.source
|
|
20626
|
+
token_source: tok.source,
|
|
20627
|
+
has_refresh_token: Boolean(tok.tokens?.refreshToken),
|
|
20628
|
+
access_token_expires_at: tok.tokens?.expiresAt ? new Date(tok.tokens.expiresAt * 1e3).toISOString() : null,
|
|
20629
|
+
scopes: tok.tokens?.scope ?? null
|
|
20264
20630
|
},
|
|
20265
20631
|
null,
|
|
20266
20632
|
2
|
|
@@ -20308,28 +20674,41 @@ if (isDirectExecution()) {
|
|
|
20308
20674
|
}
|
|
20309
20675
|
export {
|
|
20310
20676
|
DEFAULT_KEYCHAIN_SERVICE,
|
|
20677
|
+
DEFAULT_OAUTH2_SCOPES,
|
|
20678
|
+
OAuth2TokenError,
|
|
20311
20679
|
PACKAGE_NAME,
|
|
20312
20680
|
PACKAGE_VERSION,
|
|
20313
20681
|
SERVER_INSTRUCTIONS,
|
|
20314
|
-
|
|
20315
|
-
|
|
20682
|
+
buildOAuth2AuthorizeUrl,
|
|
20683
|
+
clearOAuth2ClientCredentials,
|
|
20684
|
+
clearOAuth2UserTokens,
|
|
20685
|
+
clientKeyId,
|
|
20316
20686
|
computePreflightToken,
|
|
20317
20687
|
configDirPath,
|
|
20318
|
-
consumerKeyId,
|
|
20319
20688
|
convertMarkdownFile,
|
|
20320
20689
|
createMcpServer,
|
|
20690
|
+
detectHostConfigUi,
|
|
20691
|
+
ensureAuthenticatedSession,
|
|
20692
|
+
exchangeAuthorizationCode,
|
|
20321
20693
|
extractMarkdownImageSrcs,
|
|
20694
|
+
generatePkcePair,
|
|
20695
|
+
getOAuth2AuthorizeUrl,
|
|
20696
|
+
getOAuth2Scopes,
|
|
20697
|
+
getOAuth2TokenUrl,
|
|
20698
|
+
guessMediaCategory,
|
|
20699
|
+
guessMediaType,
|
|
20322
20700
|
keychainServiceName,
|
|
20323
|
-
|
|
20324
|
-
|
|
20701
|
+
loadOAuth2ClientCredentials,
|
|
20702
|
+
loadOAuth2UserTokens,
|
|
20325
20703
|
markdownToContentState,
|
|
20704
|
+
refreshOAuth2Token,
|
|
20326
20705
|
resolveCoverImagePath,
|
|
20327
|
-
|
|
20328
|
-
|
|
20329
|
-
|
|
20330
|
-
saveUserOAuthTokens,
|
|
20706
|
+
runInteractiveSetupAndOAuth2Flow,
|
|
20707
|
+
saveOAuth2ClientCredentials,
|
|
20708
|
+
saveOAuth2UserTokens,
|
|
20331
20709
|
scanSensitiveFile,
|
|
20332
20710
|
scanText,
|
|
20333
|
-
|
|
20334
|
-
verifyPreflightToken
|
|
20711
|
+
sha256Hex,
|
|
20712
|
+
verifyPreflightToken,
|
|
20713
|
+
withOAuth2RefreshLock
|
|
20335
20714
|
};
|