@wezzard/mcp-x-articles 0.2.4 → 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 +10 -15
- package/README.md +12 -10
- package/dist/server.mjs +928 -601
- package/mcp_config.json +12 -18
- package/package.json +1 -1
- package/pi-mcp.json +1 -1
- package/plugin.json +1 -1
- package/skills/x-articles/SKILL.md +3 -3
package/dist/server.mjs
CHANGED
|
@@ -7261,11 +7261,24 @@ 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
|
}
|
|
@@ -7282,7 +7295,7 @@ function detectHostConfigUi() {
|
|
|
7282
7295
|
hasNativeConfigUi: true,
|
|
7283
7296
|
hostName: "antigravity",
|
|
7284
7297
|
configUiUrl,
|
|
7285
|
-
setupInstruction: `Open Antigravity's MCP plugin configuration UI at [X Articles](${configUiUrl}) and configure
|
|
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).`
|
|
7286
7299
|
};
|
|
7287
7300
|
}
|
|
7288
7301
|
if ((process.env.CURSOR_PLUGIN_ROOT ?? "").trim()) {
|
|
@@ -7290,14 +7303,14 @@ function detectHostConfigUi() {
|
|
|
7290
7303
|
hasNativeConfigUi: true,
|
|
7291
7304
|
hostName: "cursor",
|
|
7292
7305
|
configUiUrl: null,
|
|
7293
|
-
setupInstruction: "Open Cursor's MCP plugin settings UI and configure
|
|
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)."
|
|
7294
7307
|
};
|
|
7295
7308
|
}
|
|
7296
7309
|
return {
|
|
7297
7310
|
hasNativeConfigUi: false,
|
|
7298
7311
|
hostName: "none",
|
|
7299
7312
|
configUiUrl: null,
|
|
7300
|
-
setupInstruction: "Call `x_article_auth_status({ login: true })` to open the local browser setup form (saves
|
|
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."
|
|
7301
7314
|
};
|
|
7302
7315
|
}
|
|
7303
7316
|
function cleanEnvValue(raw) {
|
|
@@ -7305,19 +7318,25 @@ function cleanEnvValue(raw) {
|
|
|
7305
7318
|
if (!val || val.startsWith("${")) return "";
|
|
7306
7319
|
return val;
|
|
7307
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
|
+
}
|
|
7308
7327
|
function configDirPath() {
|
|
7309
7328
|
const xdg = (process.env.XDG_CONFIG_HOME ?? "").trim();
|
|
7310
7329
|
const base = xdg ? xdg : join(homedir(), ".config");
|
|
7311
7330
|
return join(base, "mcp-x-articles");
|
|
7312
7331
|
}
|
|
7313
|
-
function
|
|
7314
|
-
return join(configDirPath(), "
|
|
7332
|
+
function clientCredentialsFilePath() {
|
|
7333
|
+
return join(configDirPath(), "oauth2_client.json");
|
|
7315
7334
|
}
|
|
7316
7335
|
function tokensFilePath() {
|
|
7317
|
-
return join(configDirPath(), "
|
|
7336
|
+
return join(configDirPath(), "oauth2_tokens.json");
|
|
7318
7337
|
}
|
|
7319
|
-
function
|
|
7320
|
-
return
|
|
7338
|
+
function refreshLockFilePath() {
|
|
7339
|
+
return join(configDirPath(), "oauth2_refresh.lock");
|
|
7321
7340
|
}
|
|
7322
7341
|
function isMacKeychainAvailable() {
|
|
7323
7342
|
if (process.platform !== "darwin") return false;
|
|
@@ -7362,13 +7381,6 @@ function keychainDelete(account) {
|
|
|
7362
7381
|
} catch {
|
|
7363
7382
|
}
|
|
7364
7383
|
}
|
|
7365
|
-
function clearConsumerCredentials() {
|
|
7366
|
-
keychainDelete(CONSUMER_ACCOUNT);
|
|
7367
|
-
const file = credentialsFilePath();
|
|
7368
|
-
if (existsSync(file)) {
|
|
7369
|
-
writeAtomic0600(file, {});
|
|
7370
|
-
}
|
|
7371
|
-
}
|
|
7372
7384
|
function writeAtomic0600(filePath, data) {
|
|
7373
7385
|
const dir = configDirPath();
|
|
7374
7386
|
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
@@ -7389,14 +7401,21 @@ function readJsonSafe(filePath) {
|
|
|
7389
7401
|
return null;
|
|
7390
7402
|
}
|
|
7391
7403
|
}
|
|
7392
|
-
function
|
|
7393
|
-
|
|
7394
|
-
const
|
|
7395
|
-
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) {
|
|
7396
7415
|
return {
|
|
7397
7416
|
credentials: {
|
|
7398
|
-
|
|
7399
|
-
|
|
7417
|
+
clientId: envId,
|
|
7418
|
+
...envSecret ? { clientSecret: envSecret } : {}
|
|
7400
7419
|
},
|
|
7401
7420
|
source: "env"
|
|
7402
7421
|
};
|
|
@@ -7404,15 +7423,15 @@ function loadConsumerCredentials() {
|
|
|
7404
7423
|
if (detectHostConfigUi().hasNativeConfigUi && process.env.MCP_X_ARTICLES_ALLOW_KEYCHAIN_IN_NATIVE_UI !== "1") {
|
|
7405
7424
|
return { credentials: null, source: "none" };
|
|
7406
7425
|
}
|
|
7407
|
-
const kcRaw = keychainRead(
|
|
7426
|
+
const kcRaw = keychainRead(CLIENT_ACCOUNT);
|
|
7408
7427
|
if (kcRaw) {
|
|
7409
7428
|
try {
|
|
7410
7429
|
const parsed = JSON.parse(kcRaw);
|
|
7411
|
-
if (parsed.
|
|
7430
|
+
if (parsed.clientId) {
|
|
7412
7431
|
return {
|
|
7413
7432
|
credentials: {
|
|
7414
|
-
|
|
7415
|
-
|
|
7433
|
+
clientId: parsed.clientId,
|
|
7434
|
+
...parsed.clientSecret ? { clientSecret: parsed.clientSecret } : {}
|
|
7416
7435
|
},
|
|
7417
7436
|
source: "macos-keychain"
|
|
7418
7437
|
};
|
|
@@ -7420,50 +7439,46 @@ function loadConsumerCredentials() {
|
|
|
7420
7439
|
} catch {
|
|
7421
7440
|
}
|
|
7422
7441
|
}
|
|
7423
|
-
const fileCreds = readJsonSafe(
|
|
7424
|
-
if (fileCreds?.
|
|
7442
|
+
const fileCreds = readJsonSafe(clientCredentialsFilePath());
|
|
7443
|
+
if (fileCreds?.clientId) {
|
|
7425
7444
|
return {
|
|
7426
7445
|
credentials: {
|
|
7427
|
-
|
|
7428
|
-
|
|
7446
|
+
clientId: fileCreds.clientId,
|
|
7447
|
+
...fileCreds.clientSecret ? { clientSecret: fileCreds.clientSecret } : {}
|
|
7429
7448
|
},
|
|
7430
7449
|
source: "xdg-config"
|
|
7431
7450
|
};
|
|
7432
7451
|
}
|
|
7433
7452
|
return { credentials: null, source: "none" };
|
|
7434
7453
|
}
|
|
7435
|
-
function
|
|
7454
|
+
function saveOAuth2ClientCredentials(creds) {
|
|
7455
|
+
const trimmedSecret = (creds.clientSecret ?? "").trim();
|
|
7436
7456
|
const payload = {
|
|
7437
|
-
|
|
7438
|
-
|
|
7457
|
+
clientId: creds.clientId.trim(),
|
|
7458
|
+
...trimmedSecret ? { clientSecret: trimmedSecret } : {}
|
|
7439
7459
|
};
|
|
7440
|
-
if (keychainWrite(
|
|
7460
|
+
if (keychainWrite(CLIENT_ACCOUNT, JSON.stringify(payload))) {
|
|
7441
7461
|
return "macos-keychain";
|
|
7442
7462
|
}
|
|
7443
|
-
writeAtomic0600(
|
|
7463
|
+
writeAtomic0600(clientCredentialsFilePath(), payload);
|
|
7444
7464
|
return "xdg-config";
|
|
7445
7465
|
}
|
|
7446
|
-
function
|
|
7447
|
-
const
|
|
7448
|
-
const
|
|
7449
|
-
if (envTok && envSec) {
|
|
7450
|
-
return {
|
|
7451
|
-
tokens: { accessToken: envTok, accessSecret: envSec, savedAt: 0 },
|
|
7452
|
-
source: "env"
|
|
7453
|
-
};
|
|
7454
|
-
}
|
|
7455
|
-
const keyId = consumerKeyId(consumerKey);
|
|
7456
|
-
const kcAccount = `oauth1_user_token:${keyId}`;
|
|
7466
|
+
function readStoredOAuth2UserTokens(clientId) {
|
|
7467
|
+
const keyId = clientKeyId(clientId);
|
|
7468
|
+
const kcAccount = `oauth2_user_token:${keyId}`;
|
|
7457
7469
|
const kcRaw = keychainRead(kcAccount);
|
|
7458
7470
|
if (kcRaw) {
|
|
7459
7471
|
try {
|
|
7460
7472
|
const parsed = JSON.parse(kcRaw);
|
|
7461
|
-
if (parsed.accessToken
|
|
7473
|
+
if (parsed.accessToken || parsed.refreshToken) {
|
|
7462
7474
|
return {
|
|
7463
7475
|
tokens: {
|
|
7464
|
-
accessToken: parsed.accessToken,
|
|
7465
|
-
|
|
7466
|
-
|
|
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 } : {}
|
|
7467
7482
|
},
|
|
7468
7483
|
source: "macos-keychain"
|
|
7469
7484
|
};
|
|
@@ -7473,26 +7488,68 @@ function loadUserOAuthTokens(consumerKey) {
|
|
|
7473
7488
|
}
|
|
7474
7489
|
const map = readJsonSafe(tokensFilePath());
|
|
7475
7490
|
const entry = map?.[keyId];
|
|
7476
|
-
if (entry
|
|
7491
|
+
if (entry && (entry.accessToken || entry.refreshToken)) {
|
|
7477
7492
|
return {
|
|
7478
7493
|
tokens: {
|
|
7479
|
-
accessToken: entry.accessToken,
|
|
7480
|
-
|
|
7481
|
-
|
|
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 } : {}
|
|
7482
7500
|
},
|
|
7483
7501
|
source: "xdg-config"
|
|
7484
7502
|
};
|
|
7485
7503
|
}
|
|
7486
7504
|
return { tokens: null, source: "none" };
|
|
7487
7505
|
}
|
|
7488
|
-
function
|
|
7489
|
-
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);
|
|
7490
7544
|
const record2 = {
|
|
7491
|
-
accessToken: accessToken.trim(),
|
|
7492
|
-
|
|
7493
|
-
|
|
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() } : {}
|
|
7494
7551
|
};
|
|
7495
|
-
if (keychainWrite(`
|
|
7552
|
+
if (keychainWrite(`oauth2_user_token:${keyId}`, JSON.stringify(record2))) {
|
|
7496
7553
|
return "macos-keychain";
|
|
7497
7554
|
}
|
|
7498
7555
|
const existing = readJsonSafe(tokensFilePath()) ?? {};
|
|
@@ -7500,9 +7557,9 @@ function saveUserOAuthTokens(consumerKey, accessToken, accessSecret) {
|
|
|
7500
7557
|
writeAtomic0600(tokensFilePath(), existing);
|
|
7501
7558
|
return "xdg-config";
|
|
7502
7559
|
}
|
|
7503
|
-
function
|
|
7504
|
-
const keyId =
|
|
7505
|
-
keychainDelete(`
|
|
7560
|
+
function clearOAuth2UserTokens(clientId) {
|
|
7561
|
+
const keyId = clientKeyId(clientId);
|
|
7562
|
+
keychainDelete(`oauth2_user_token:${keyId}`);
|
|
7506
7563
|
const file = tokensFilePath();
|
|
7507
7564
|
const existing = readJsonSafe(file);
|
|
7508
7565
|
if (existing && keyId in existing) {
|
|
@@ -7510,61 +7567,179 @@ function clearUserOAuthTokens(consumerKey) {
|
|
|
7510
7567
|
writeAtomic0600(file, existing);
|
|
7511
7568
|
}
|
|
7512
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
|
+
}
|
|
7513
7610
|
|
|
7514
|
-
// src/
|
|
7611
|
+
// src/oauth2.ts
|
|
7515
7612
|
import { execFile } from "node:child_process";
|
|
7516
|
-
import {
|
|
7613
|
+
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
7517
7614
|
import { createServer } from "node:http";
|
|
7518
|
-
|
|
7519
|
-
|
|
7520
|
-
|
|
7521
|
-
function rfc3986Encode(value) {
|
|
7522
|
-
return encodeURIComponent(value).replace(
|
|
7523
|
-
/[!'()*]/g,
|
|
7524
|
-
(ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`
|
|
7525
|
-
);
|
|
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(/\/+$/, "");
|
|
7526
7618
|
}
|
|
7527
|
-
function
|
|
7528
|
-
|
|
7529
|
-
|
|
7530
|
-
|
|
7531
|
-
const
|
|
7532
|
-
|
|
7533
|
-
|
|
7534
|
-
|
|
7535
|
-
|
|
7536
|
-
|
|
7537
|
-
|
|
7538
|
-
|
|
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"
|
|
7539
7664
|
};
|
|
7540
|
-
|
|
7541
|
-
|
|
7542
|
-
|
|
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);
|
|
7543
7673
|
}
|
|
7544
|
-
for (const [k, v2] of
|
|
7545
|
-
|
|
7674
|
+
for (const [k, v2] of Object.entries(options.params)) {
|
|
7675
|
+
body.set(k, v2);
|
|
7546
7676
|
}
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
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 };
|
|
7550
7689
|
}
|
|
7551
7690
|
}
|
|
7552
|
-
|
|
7553
|
-
|
|
7554
|
-
|
|
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
|
+
}
|
|
7555
7742
|
});
|
|
7556
|
-
const normalizedParams = pairs.map(([k, v2]) => `${k}=${v2}`).join("&");
|
|
7557
|
-
const baseString = `${method}&${rfc3986Encode(baseUri)}&${rfc3986Encode(normalizedParams)}`;
|
|
7558
|
-
const signingKey = `${rfc3986Encode(options.credentials.consumerSecret)}&${rfc3986Encode(
|
|
7559
|
-
options.credentials.tokenSecret ?? ""
|
|
7560
|
-
)}`;
|
|
7561
|
-
const signature = createHmac("sha1", signingKey).update(baseString, "utf8").digest("base64");
|
|
7562
|
-
const headerEntries = [
|
|
7563
|
-
...Object.entries(oauthParams),
|
|
7564
|
-
["oauth_signature", signature]
|
|
7565
|
-
].sort((a, b2) => a[0] < b2[0] ? -1 : a[0] > b2[0] ? 1 : 0);
|
|
7566
|
-
const headerBody = headerEntries.map(([k, v2]) => `${rfc3986Encode(k)}="${rfc3986Encode(v2)}"`).join(", ");
|
|
7567
|
-
return `OAuth ${headerBody}`;
|
|
7568
7743
|
}
|
|
7569
7744
|
function openBrowserUrl(targetUrl) {
|
|
7570
7745
|
if (process.env.MCP_X_ARTICLES_NO_BROWSER === "1") return;
|
|
@@ -7582,7 +7757,7 @@ function openBrowserUrl(targetUrl) {
|
|
|
7582
7757
|
function escapeHtml(raw) {
|
|
7583
7758
|
return raw.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
7584
7759
|
}
|
|
7585
|
-
function renderHtmlPage(title, bodyHtml
|
|
7760
|
+
function renderHtmlPage(title, bodyHtml) {
|
|
7586
7761
|
return `<!DOCTYPE html>
|
|
7587
7762
|
<html lang="en">
|
|
7588
7763
|
<head>
|
|
@@ -7593,426 +7768,346 @@ function renderHtmlPage(title, bodyHtml, allowOpenLink = false) {
|
|
|
7593
7768
|
:root { color-scheme: light dark; }
|
|
7594
7769
|
body {
|
|
7595
7770
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
7596
|
-
|
|
7597
|
-
|
|
7598
|
-
|
|
7771
|
+
max-width: 560px;
|
|
7772
|
+
margin: 48px auto;
|
|
7773
|
+
padding: 0 20px;
|
|
7774
|
+
line-height: 1.55;
|
|
7599
7775
|
}
|
|
7600
7776
|
.card {
|
|
7601
|
-
|
|
7602
|
-
border
|
|
7603
|
-
padding:
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
|
|
7607
|
-
|
|
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; }
|
|
7608
7785
|
input[type="text"], input[type="password"] {
|
|
7609
|
-
width: 100%;
|
|
7610
|
-
|
|
7611
|
-
|
|
7612
|
-
|
|
7613
|
-
|
|
7614
|
-
|
|
7615
|
-
|
|
7616
|
-
background:
|
|
7617
|
-
|
|
7618
|
-
|
|
7619
|
-
|
|
7620
|
-
|
|
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; }
|
|
7621
7809
|
}
|
|
7622
7810
|
.err {
|
|
7623
|
-
|
|
7624
|
-
|
|
7625
|
-
|
|
7626
|
-
|
|
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; }
|
|
7627
7820
|
</style>
|
|
7628
7821
|
</head>
|
|
7629
7822
|
<body>
|
|
7630
7823
|
<div class="card">
|
|
7631
7824
|
${bodyHtml}
|
|
7632
7825
|
</div>
|
|
7633
|
-
${allowOpenLink ? "" : ""}
|
|
7634
7826
|
</body>
|
|
7635
7827
|
</html>`;
|
|
7636
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
|
+
}
|
|
7637
7837
|
async function readFormBody(req) {
|
|
7638
7838
|
const chunks = [];
|
|
7639
7839
|
let total = 0;
|
|
7640
7840
|
for await (const chunk of req) {
|
|
7641
|
-
const buf =
|
|
7841
|
+
const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
7642
7842
|
total += buf.length;
|
|
7643
7843
|
if (total > 32 * 1024) {
|
|
7644
|
-
throw new Error("
|
|
7844
|
+
throw new Error("Request body too large.");
|
|
7645
7845
|
}
|
|
7646
7846
|
chunks.push(buf);
|
|
7647
7847
|
}
|
|
7648
7848
|
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
7649
7849
|
}
|
|
7650
|
-
|
|
7651
|
-
const
|
|
7652
|
-
|
|
7653
|
-
|
|
7654
|
-
|
|
7655
|
-
|
|
7656
|
-
|
|
7657
|
-
|
|
7658
|
-
|
|
7659
|
-
|
|
7660
|
-
|
|
7661
|
-
});
|
|
7662
|
-
const body = await resp.text();
|
|
7663
|
-
if (!resp.ok) {
|
|
7664
|
-
return { ok: false, status: resp.status, body };
|
|
7665
|
-
}
|
|
7666
|
-
const params = new URLSearchParams(body);
|
|
7667
|
-
const requestToken = params.get("oauth_token") ?? "";
|
|
7668
|
-
const requestTokenSecret = params.get("oauth_token_secret") ?? "";
|
|
7669
|
-
if (!requestToken || !requestTokenSecret) {
|
|
7670
|
-
return { ok: false, status: 500, body: `Malformed request_token response: ${body}` };
|
|
7671
|
-
}
|
|
7672
|
-
return { ok: true, requestToken, requestTokenSecret };
|
|
7673
|
-
}
|
|
7674
|
-
async function exchangeXAccessToken(options) {
|
|
7675
|
-
const url = `${getOAuthBaseUrl()}/oauth/access_token`;
|
|
7676
|
-
const auth = signOAuth1Header({
|
|
7677
|
-
method: "POST",
|
|
7678
|
-
url,
|
|
7679
|
-
credentials: {
|
|
7680
|
-
consumerKey: options.consumerKey,
|
|
7681
|
-
consumerSecret: options.consumerSecret,
|
|
7682
|
-
tokenKey: options.requestToken,
|
|
7683
|
-
tokenSecret: options.requestTokenSecret
|
|
7684
|
-
},
|
|
7685
|
-
extraOAuthParams: { oauth_verifier: options.verifier }
|
|
7686
|
-
});
|
|
7687
|
-
const resp = await fetch(url, {
|
|
7688
|
-
method: "POST",
|
|
7689
|
-
headers: { Authorization: auth }
|
|
7690
|
-
});
|
|
7691
|
-
const body = await resp.text();
|
|
7692
|
-
if (!resp.ok) {
|
|
7693
|
-
throw new Error(`Failed to exchange X OAuth access token (HTTP ${resp.status}): ${body}`);
|
|
7694
|
-
}
|
|
7695
|
-
const params = new URLSearchParams(body);
|
|
7696
|
-
const accessToken = params.get("oauth_token") ?? "";
|
|
7697
|
-
const accessSecret = params.get("oauth_token_secret") ?? "";
|
|
7698
|
-
if (!accessToken || !accessSecret) {
|
|
7699
|
-
throw new Error(`Malformed X OAuth access_token response: ${body}`);
|
|
7700
|
-
}
|
|
7701
|
-
return { accessToken, accessSecret };
|
|
7702
|
-
}
|
|
7703
|
-
async function listenWithRandomFallback(server, host, preferredPort) {
|
|
7704
|
-
if (preferredPort > 0) {
|
|
7705
|
-
try {
|
|
7706
|
-
await new Promise((resolveListen, rejectListen) => {
|
|
7707
|
-
const onErr = (err) => {
|
|
7708
|
-
server.off("listening", onListening);
|
|
7709
|
-
rejectListen(err);
|
|
7710
|
-
};
|
|
7711
|
-
const onListening = () => {
|
|
7712
|
-
server.off("error", onErr);
|
|
7713
|
-
resolveListen();
|
|
7714
|
-
};
|
|
7715
|
-
server.once("error", onErr);
|
|
7716
|
-
server.once("listening", onListening);
|
|
7717
|
-
server.listen(preferredPort, host);
|
|
7718
|
-
});
|
|
7719
|
-
const addr2 = server.address();
|
|
7720
|
-
return { actualPort: addr2.port, usedFallbackPort: false };
|
|
7721
|
-
} catch (err) {
|
|
7722
|
-
const code = err?.code;
|
|
7723
|
-
if (code !== "EADDRINUSE" && code !== "EACCES") {
|
|
7724
|
-
throw err;
|
|
7725
|
-
}
|
|
7726
|
-
process.stderr.write(
|
|
7727
|
-
`[@wezzard/mcp-x-articles] Port ${preferredPort} is in use; falling back to an OS-assigned random port with OAuth 1.0a PIN mode.
|
|
7728
|
-
`
|
|
7729
|
-
);
|
|
7730
|
-
}
|
|
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
|
+
};
|
|
7731
7861
|
}
|
|
7732
|
-
await new Promise((resolveListen, rejectListen) => {
|
|
7733
|
-
server.once("error", rejectListen);
|
|
7734
|
-
server.listen(0, host, () => {
|
|
7735
|
-
server.off("error", rejectListen);
|
|
7736
|
-
resolveListen();
|
|
7737
|
-
});
|
|
7738
|
-
});
|
|
7739
|
-
const addr = server.address();
|
|
7740
|
-
return { actualPort: addr.port, usedFallbackPort: true };
|
|
7741
|
-
}
|
|
7742
|
-
async function runInteractiveSetupAndOAuth1Flow(options) {
|
|
7743
7862
|
const host = (process.env.X_OAUTH_CALLBACK_HOST ?? "127.0.0.1").trim() || "127.0.0.1";
|
|
7744
7863
|
const rawPort = (process.env.X_OAUTH_CALLBACK_PORT ?? "8976").trim();
|
|
7745
|
-
const
|
|
7746
|
-
const
|
|
7747
|
-
const
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
|
|
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) {
|
|
7751
7870
|
const hostUi = detectHostConfigUi();
|
|
7752
|
-
if (!
|
|
7871
|
+
if (!options.existingCredentials && hostUi.hasNativeConfigUi) {
|
|
7753
7872
|
throw new Error(
|
|
7754
|
-
`Missing X OAuth
|
|
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.`
|
|
7755
7874
|
);
|
|
7756
7875
|
}
|
|
7757
|
-
|
|
7758
|
-
|
|
7759
|
-
let
|
|
7760
|
-
let
|
|
7761
|
-
const
|
|
7762
|
-
|
|
7763
|
-
|
|
7764
|
-
|
|
7765
|
-
|
|
7766
|
-
|
|
7767
|
-
|
|
7768
|
-
);
|
|
7769
|
-
res.end(html);
|
|
7770
|
-
};
|
|
7771
|
-
let resolveDone;
|
|
7772
|
-
let rejectDone;
|
|
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;
|
|
7773
7887
|
const donePromise = new Promise((res, rej) => {
|
|
7774
|
-
|
|
7775
|
-
|
|
7888
|
+
finishResolve = res;
|
|
7889
|
+
finishReject = rej;
|
|
7776
7890
|
});
|
|
7777
|
-
const
|
|
7778
|
-
|
|
7779
|
-
|
|
7780
|
-
|
|
7781
|
-
|
|
7782
|
-
|
|
7783
|
-
cbUrl
|
|
7784
|
-
);
|
|
7785
|
-
if (attempt.ok) {
|
|
7786
|
-
activeReqToken = attempt.requestToken;
|
|
7787
|
-
activeReqSecret = attempt.requestTokenSecret;
|
|
7788
|
-
return `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7789
|
-
}
|
|
7790
|
-
if (attempt.body.toLowerCase().includes("callback") || attempt.status === 401 || attempt.status === 403 || attempt.status === 400) {
|
|
7791
|
-
const oobAttempt = await requestXToken(
|
|
7792
|
-
currentCreds.consumerKey,
|
|
7793
|
-
currentCreds.consumerSecret,
|
|
7794
|
-
"oob"
|
|
7795
|
-
);
|
|
7796
|
-
if (oobAttempt.ok) {
|
|
7797
|
-
useOobMode = true;
|
|
7798
|
-
activeReqToken = oobAttempt.requestToken;
|
|
7799
|
-
activeReqSecret = oobAttempt.requestTokenSecret;
|
|
7800
|
-
return `http://${host}:${actualPort}/pin?s=${csrfSecret}`;
|
|
7801
|
-
}
|
|
7802
|
-
}
|
|
7803
|
-
throw new Error(`X OAuth request_token failed (HTTP ${attempt.status}): ${attempt.body}`);
|
|
7804
|
-
}
|
|
7805
|
-
const oobRes = await requestXToken(
|
|
7806
|
-
currentCreds.consumerKey,
|
|
7807
|
-
currentCreds.consumerSecret,
|
|
7808
|
-
"oob"
|
|
7809
|
-
);
|
|
7810
|
-
if (!oobRes.ok) {
|
|
7811
|
-
throw new Error(`X OAuth request_token (oob) failed (HTTP ${oobRes.status}): ${oobRes.body}`);
|
|
7812
|
-
}
|
|
7813
|
-
activeReqToken = oobRes.requestToken;
|
|
7814
|
-
activeReqSecret = oobRes.requestTokenSecret;
|
|
7815
|
-
return `http://${host}:${actualPort}/pin?s=${csrfSecret}`;
|
|
7816
|
-
};
|
|
7817
|
-
const renderSetupForm = (errorMsg) => renderHtmlPage(
|
|
7818
|
-
"Setup @wezzard/mcp-x-articles",
|
|
7819
|
-
[
|
|
7820
|
-
"<h1>Connect @wezzard/mcp-x-articles</h1>",
|
|
7821
|
-
"<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>",
|
|
7822
|
-
errorMsg ? `<div class="err">${escapeHtml(errorMsg)}</div>` : "",
|
|
7823
|
-
'<form method="POST" action="/setup">',
|
|
7824
|
-
`<input type="hidden" name="s" value="${csrfSecret}" />`,
|
|
7825
|
-
'<label for="ck">X API Key (Consumer Key)</label>',
|
|
7826
|
-
'<input id="ck" name="consumer_key" type="text" autocomplete="off" required />',
|
|
7827
|
-
'<label for="cs">X API Key Secret (Consumer Secret)</label>',
|
|
7828
|
-
'<input id="cs" name="consumer_secret" type="password" autocomplete="off" required />',
|
|
7829
|
-
'<button type="submit">Save to Keychain & Authorize on X →</button>',
|
|
7830
|
-
"</form>"
|
|
7831
|
-
].join("\n")
|
|
7832
|
-
);
|
|
7833
|
-
const renderPinForm = (authorizeUrl, errorMsg) => renderHtmlPage(
|
|
7834
|
-
"Authorize @wezzard/mcp-x-articles",
|
|
7835
|
-
[
|
|
7836
|
-
"<h1>Enter Your X Authorization PIN</h1>",
|
|
7837
|
-
"<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>",
|
|
7838
|
-
`<p><a class="btn" href="${escapeHtml(authorizeUrl)}" target="_blank" rel="noopener noreferrer">1. Open X Authorization Page ↗</a></p>`,
|
|
7839
|
-
errorMsg ? `<div class="err">${escapeHtml(errorMsg)}</div>` : "",
|
|
7840
|
-
'<form method="POST" action="/pin">',
|
|
7841
|
-
`<input type="hidden" name="s" value="${csrfSecret}" />`,
|
|
7842
|
-
'<label for="pin">2. X OAuth PIN Code</label>',
|
|
7843
|
-
'<input id="pin" name="verifier" type="text" inputmode="numeric" autocomplete="one-time-code" placeholder="1234567" required />',
|
|
7844
|
-
'<button type="submit">Complete Authentication</button>',
|
|
7845
|
-
"</form>"
|
|
7846
|
-
].join("\n"),
|
|
7847
|
-
true
|
|
7848
|
-
);
|
|
7849
|
-
const server = createServer(async (req, res) => {
|
|
7850
|
-
try {
|
|
7851
|
-
const reqUrl = new URL(req.url ?? "/", `http://${host}:${actualPort}`);
|
|
7852
|
-
if (req.method === "GET" && reqUrl.pathname === "/setup") {
|
|
7853
|
-
if (reqUrl.searchParams.get("s") !== csrfSecret) {
|
|
7854
|
-
sendHtml(res, 403, renderHtmlPage("Forbidden", "<h1>Invalid setup session token.</h1>"));
|
|
7855
|
-
return;
|
|
7856
|
-
}
|
|
7857
|
-
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>");
|
|
7858
7897
|
return;
|
|
7859
7898
|
}
|
|
7860
|
-
|
|
7861
|
-
|
|
7862
|
-
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
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>");
|
|
7884
7939
|
return;
|
|
7885
7940
|
}
|
|
7886
|
-
|
|
7887
|
-
|
|
7888
|
-
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
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();
|
|
7893
7949
|
return;
|
|
7894
7950
|
}
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
7898
|
-
|
|
7899
|
-
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
if (!verifier) {
|
|
7903
|
-
const authUrl = `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7904
|
-
sendHtml(res, 400, renderPinForm(authUrl, "Please enter the PIN code from X."));
|
|
7905
|
-
return;
|
|
7906
|
-
}
|
|
7951
|
+
const nextCreds = {
|
|
7952
|
+
clientId,
|
|
7953
|
+
...clientSecret ? { clientSecret } : {}
|
|
7954
|
+
};
|
|
7955
|
+
credentialSource = saveOAuth2ClientCredentials(nextCreds);
|
|
7956
|
+
credentials = nextCreds;
|
|
7957
|
+
if (refreshToken) {
|
|
7907
7958
|
try {
|
|
7908
|
-
const
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
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
|
|
7914
7971
|
});
|
|
7915
7972
|
sendHtml(
|
|
7916
7973
|
res,
|
|
7917
7974
|
200,
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
"<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>"
|
|
7921
|
-
)
|
|
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>"
|
|
7922
7977
|
);
|
|
7923
|
-
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
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
|
|
7933
7988
|
});
|
|
7934
7989
|
} catch (err) {
|
|
7935
|
-
const authUrl = `${getOAuthBaseUrl()}/oauth/authorize?oauth_token=${encodeURIComponent(activeReqToken)}`;
|
|
7936
7990
|
const msg = err instanceof Error ? err.message : String(err);
|
|
7937
|
-
|
|
7991
|
+
res.writeHead(302, {
|
|
7992
|
+
Location: `/setup?s=${csrfToken}&error=${encodeURIComponent(msg)}`
|
|
7993
|
+
});
|
|
7994
|
+
res.end();
|
|
7938
7995
|
}
|
|
7939
7996
|
return;
|
|
7940
7997
|
}
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
|
|
7946
|
-
|
|
7947
|
-
|
|
7948
|
-
|
|
7949
|
-
|
|
7950
|
-
|
|
7951
|
-
|
|
7952
|
-
|
|
7953
|
-
|
|
7954
|
-
|
|
7955
|
-
|
|
7956
|
-
|
|
7957
|
-
|
|
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
|
|
7958
8037
|
});
|
|
7959
8038
|
sendHtml(
|
|
7960
8039
|
res,
|
|
7961
8040
|
200,
|
|
7962
|
-
|
|
7963
|
-
|
|
7964
|
-
"<h1>Authentication Complete</h1><p>Authorization succeeded. You may close this tab and return to your agent.</p>"
|
|
7965
|
-
)
|
|
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>"
|
|
7966
8043
|
);
|
|
7967
|
-
|
|
7968
|
-
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
|
|
7972
|
-
|
|
7973
|
-
|
|
7974
|
-
|
|
7975
|
-
|
|
7976
|
-
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
|
|
7977
8053
|
});
|
|
7978
|
-
|
|
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));
|
|
7979
8058
|
}
|
|
7980
|
-
|
|
7981
|
-
res.end("Not found.");
|
|
7982
|
-
} catch (err) {
|
|
7983
|
-
clearTimeout(timer);
|
|
7984
|
-
server.close();
|
|
7985
|
-
rejectDone(err instanceof Error ? err : new Error(String(err)));
|
|
8059
|
+
return;
|
|
7986
8060
|
}
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
7990
|
-
|
|
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}`;
|
|
7991
8090
|
const timer = setTimeout(() => {
|
|
7992
|
-
|
|
7993
|
-
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.`));
|
|
7994
8092
|
}, timeoutSec * 1e3);
|
|
7995
|
-
let entryUrl;
|
|
7996
8093
|
try {
|
|
7997
|
-
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
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 {
|
|
8003
8104
|
clearTimeout(timer);
|
|
8004
|
-
server
|
|
8005
|
-
throw err;
|
|
8105
|
+
server?.close();
|
|
8006
8106
|
}
|
|
8007
|
-
process.stderr.write(`[@wezzard/mcp-x-articles] Opening browser for X authentication: ${entryUrl}
|
|
8008
|
-
`);
|
|
8009
|
-
options.onServerReady?.(entryUrl);
|
|
8010
|
-
openBrowserUrl(entryUrl);
|
|
8011
|
-
return donePromise;
|
|
8012
8107
|
}
|
|
8013
8108
|
|
|
8014
8109
|
// src/server.ts
|
|
8015
|
-
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";
|
|
8016
8111
|
import { dirname as dirname3, resolve as resolve4 } from "node:path";
|
|
8017
8112
|
|
|
8018
8113
|
// node_modules/zod/v4/core/util.js
|
|
@@ -19298,7 +19393,7 @@ function convertMarkdownFile(markdownPath, options = {}) {
|
|
|
19298
19393
|
}
|
|
19299
19394
|
|
|
19300
19395
|
// src/preflight-token.ts
|
|
19301
|
-
import { createHash as
|
|
19396
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
19302
19397
|
import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
|
|
19303
19398
|
import { dirname as dirname2, resolve as resolve2 } from "node:path";
|
|
19304
19399
|
|
|
@@ -19391,7 +19486,7 @@ function scanSensitiveFile(markdownPath, alsoPaths = []) {
|
|
|
19391
19486
|
|
|
19392
19487
|
// src/preflight-token.ts
|
|
19393
19488
|
function sha256Bytes(buf) {
|
|
19394
|
-
return
|
|
19489
|
+
return createHash3("sha256").update(buf).digest("hex");
|
|
19395
19490
|
}
|
|
19396
19491
|
function resolveCoverImagePath(markdownPath, explicitCoverPath, omitCover) {
|
|
19397
19492
|
if (omitCover) return void 0;
|
|
@@ -19461,6 +19556,7 @@ function verifyPreflightToken(providedToken, input) {
|
|
|
19461
19556
|
import { readFileSync as readFileSync5 } from "node:fs";
|
|
19462
19557
|
import { extname, resolve as resolve3 } from "node:path";
|
|
19463
19558
|
var CHUNK_SIZE_BYTES = 25e5;
|
|
19559
|
+
var REFRESH_BUFFER_SECONDS = 300;
|
|
19464
19560
|
function guessMediaType(pathOrUrl) {
|
|
19465
19561
|
const clean = pathOrUrl.split("?")[0].split("#")[0];
|
|
19466
19562
|
const ext = extname(clean).toLowerCase();
|
|
@@ -19479,18 +19575,66 @@ function guessMediaType(pathOrUrl) {
|
|
|
19479
19575
|
};
|
|
19480
19576
|
return mapping[ext] ?? "image/png";
|
|
19481
19577
|
}
|
|
19482
|
-
function
|
|
19483
|
-
|
|
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
|
+
});
|
|
19484
19633
|
}
|
|
19485
|
-
async function
|
|
19634
|
+
async function rawBearerJsonRequest(options) {
|
|
19486
19635
|
const url = `${getApiBaseUrl()}${options.pathWithQuery}`;
|
|
19487
|
-
const authHeader = signOAuth1Header({
|
|
19488
|
-
method: options.method,
|
|
19489
|
-
url,
|
|
19490
|
-
credentials: options.signingCreds
|
|
19491
|
-
});
|
|
19492
19636
|
const headers = {
|
|
19493
|
-
Authorization:
|
|
19637
|
+
Authorization: `Bearer ${options.accessToken}`,
|
|
19494
19638
|
"X-B3-Flags": (process.env.X_B3_FLAGS ?? "1").trim() || "1"
|
|
19495
19639
|
};
|
|
19496
19640
|
let bodyStr;
|
|
@@ -19517,93 +19661,222 @@ async function signedJsonRequest(options) {
|
|
|
19517
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}`
|
|
19518
19662
|
);
|
|
19519
19663
|
}
|
|
19520
|
-
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.`;
|
|
19521
19706
|
}
|
|
19522
19707
|
async function ensureAuthenticatedSession(options) {
|
|
19523
|
-
|
|
19524
|
-
let
|
|
19525
|
-
let
|
|
19526
|
-
|
|
19527
|
-
|
|
19528
|
-
|
|
19529
|
-
|
|
19530
|
-
|
|
19531
|
-
tokenSecret: tokens.accessSecret
|
|
19532
|
-
};
|
|
19533
|
-
const probe = await signedJsonRequest({
|
|
19534
|
-
method: "GET",
|
|
19535
|
-
pathWithQuery: "/2/users/me",
|
|
19536
|
-
signingCreds: signingCreds2
|
|
19537
|
-
});
|
|
19538
|
-
if (probe.status !== 401) {
|
|
19539
|
-
return {
|
|
19540
|
-
signingCreds: signingCreds2,
|
|
19541
|
-
credentialSource,
|
|
19542
|
-
tokenSource,
|
|
19543
|
-
user: probe.data?.data
|
|
19544
|
-
};
|
|
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}`);
|
|
19545
19716
|
}
|
|
19546
|
-
|
|
19547
|
-
|
|
19548
|
-
|
|
19549
|
-
}
|
|
19550
|
-
|
|
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
|
+
}
|
|
19551
19766
|
}
|
|
19552
19767
|
}
|
|
19553
|
-
if (!
|
|
19554
|
-
const hostUi = detectHostConfigUi();
|
|
19555
|
-
if (!credentials && hostUi.hasNativeConfigUi) {
|
|
19556
|
-
throw new Error(`Missing X OAuth Consumer Key and Secret. ${hostUi.setupInstruction}`);
|
|
19557
|
-
}
|
|
19768
|
+
if (!tokens) {
|
|
19558
19769
|
if (!options.allowInteractiveLogin) {
|
|
19559
|
-
|
|
19560
|
-
throw new Error(`Missing X OAuth Consumer Key and Secret. ${hostUi.setupInstruction}`);
|
|
19561
|
-
}
|
|
19562
|
-
throw new Error(
|
|
19563
|
-
hostUi.hasNativeConfigUi ? `No user OAuth 1.0a token is configured yet. Either configure X_OAUTH_ACCESS_TOKEN and X_OAUTH_ACCESS_TOKEN_SECRET in ${hostUi.configUiUrl ? `[X Articles](${hostUi.configUiUrl})` : "your host's MCP plugin configuration UI"}, or call \`x_article_auth_status({ login: true })\` to authorize in your browser.` : "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."
|
|
19564
|
-
);
|
|
19770
|
+
throw new Error(buildMissingTokenHint(credentialSource));
|
|
19565
19771
|
}
|
|
19566
|
-
const interactive = await
|
|
19772
|
+
const interactive = await runInteractiveSetupAndOAuth2Flow({
|
|
19567
19773
|
existingCredentials: credentials,
|
|
19568
19774
|
existingCredentialSource: credentialSource
|
|
19569
19775
|
});
|
|
19570
19776
|
credentials = interactive.credentials;
|
|
19571
19777
|
credentialSource = interactive.credentialSource;
|
|
19572
|
-
|
|
19573
|
-
|
|
19574
|
-
|
|
19575
|
-
|
|
19576
|
-
|
|
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
|
+
}
|
|
19577
19790
|
tokens = {
|
|
19578
19791
|
accessToken: interactive.accessToken,
|
|
19579
|
-
|
|
19580
|
-
|
|
19792
|
+
refreshToken: interactive.refreshToken,
|
|
19793
|
+
expiresAt: interactive.expiresAt,
|
|
19794
|
+
scope: interactive.scope,
|
|
19795
|
+
savedAt: Math.floor(Date.now() / 1e3),
|
|
19796
|
+
...seedHash ? { seedRefreshTokenHash: seedHash } : {}
|
|
19581
19797
|
};
|
|
19582
19798
|
}
|
|
19583
|
-
const
|
|
19584
|
-
|
|
19585
|
-
|
|
19586
|
-
|
|
19587
|
-
|
|
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
|
|
19588
19809
|
};
|
|
19589
|
-
let user;
|
|
19590
19810
|
if (options.verifyProbe) {
|
|
19591
|
-
|
|
19592
|
-
|
|
19593
|
-
|
|
19594
|
-
|
|
19595
|
-
|
|
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
|
+
}
|
|
19596
19872
|
if (probe.status >= 400) {
|
|
19597
|
-
throw new Error(
|
|
19873
|
+
throw new Error(
|
|
19874
|
+
`X API user verification failed (HTTP ${probe.status}): ${JSON.stringify(probe.data)}`
|
|
19875
|
+
);
|
|
19598
19876
|
}
|
|
19599
|
-
user = probe.data?.data;
|
|
19877
|
+
session.user = probe.data?.data;
|
|
19600
19878
|
}
|
|
19601
|
-
return
|
|
19602
|
-
signingCreds,
|
|
19603
|
-
credentialSource,
|
|
19604
|
-
tokenSource,
|
|
19605
|
-
user
|
|
19606
|
-
};
|
|
19879
|
+
return session;
|
|
19607
19880
|
}
|
|
19608
19881
|
async function loadImageBytes(pathOrUrl) {
|
|
19609
19882
|
if (isRemoteUrl(pathOrUrl)) {
|
|
@@ -19627,11 +19900,11 @@ async function loadImageBytes(pathOrUrl) {
|
|
|
19627
19900
|
};
|
|
19628
19901
|
}
|
|
19629
19902
|
async function uploadMediaBuffer(options) {
|
|
19630
|
-
const mediaCategory = options.mediaCategory ??
|
|
19631
|
-
const initResp = await
|
|
19903
|
+
const mediaCategory = options.mediaCategory ?? guessMediaCategory(options.mediaType);
|
|
19904
|
+
const initResp = await authorizedJsonRequest({
|
|
19632
19905
|
method: "POST",
|
|
19633
19906
|
pathWithQuery: "/2/media/upload/initialize",
|
|
19634
|
-
|
|
19907
|
+
session: options.session,
|
|
19635
19908
|
jsonBody: {
|
|
19636
19909
|
media_category: mediaCategory,
|
|
19637
19910
|
media_type: options.mediaType,
|
|
@@ -19650,10 +19923,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19650
19923
|
let segmentIndex = 0;
|
|
19651
19924
|
for (let offset = 0; offset < options.bytes.length; offset += CHUNK_SIZE_BYTES) {
|
|
19652
19925
|
const chunk = options.bytes.subarray(offset, offset + CHUNK_SIZE_BYTES);
|
|
19653
|
-
const appendResp = await
|
|
19926
|
+
const appendResp = await authorizedJsonRequest({
|
|
19654
19927
|
method: "POST",
|
|
19655
19928
|
pathWithQuery: `/2/media/upload/${encodeURIComponent(mediaId)}/append`,
|
|
19656
|
-
|
|
19929
|
+
session: options.session,
|
|
19657
19930
|
jsonBody: {
|
|
19658
19931
|
media: chunk.toString("base64"),
|
|
19659
19932
|
segment_index: segmentIndex
|
|
@@ -19666,10 +19939,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19666
19939
|
}
|
|
19667
19940
|
segmentIndex += 1;
|
|
19668
19941
|
}
|
|
19669
|
-
const finResp = await
|
|
19942
|
+
const finResp = await authorizedJsonRequest({
|
|
19670
19943
|
method: "POST",
|
|
19671
19944
|
pathWithQuery: `/2/media/upload/${encodeURIComponent(mediaId)}/finalize`,
|
|
19672
|
-
|
|
19945
|
+
session: options.session
|
|
19673
19946
|
});
|
|
19674
19947
|
if (finResp.status >= 400) {
|
|
19675
19948
|
throw new Error(
|
|
@@ -19680,10 +19953,10 @@ async function uploadMediaBuffer(options) {
|
|
|
19680
19953
|
while (proc && (proc.state === "pending" || proc.state === "in_progress")) {
|
|
19681
19954
|
const waitSeconds = Math.max(1, Number(proc.check_after_secs ?? 2));
|
|
19682
19955
|
await new Promise((r) => setTimeout(r, waitSeconds * 1e3));
|
|
19683
|
-
const statusResp = await
|
|
19956
|
+
const statusResp = await authorizedJsonRequest({
|
|
19684
19957
|
method: "GET",
|
|
19685
19958
|
pathWithQuery: `/2/media/upload?media_id=${encodeURIComponent(mediaId)}&command=STATUS`,
|
|
19686
|
-
|
|
19959
|
+
session: options.session
|
|
19687
19960
|
});
|
|
19688
19961
|
if (statusResp.status >= 400) {
|
|
19689
19962
|
throw new Error(
|
|
@@ -19712,10 +19985,10 @@ async function createXArticleDraft(options) {
|
|
|
19712
19985
|
media_id: options.coverMediaId
|
|
19713
19986
|
};
|
|
19714
19987
|
}
|
|
19715
|
-
const resp = await
|
|
19988
|
+
const resp = await authorizedJsonRequest({
|
|
19716
19989
|
method: "POST",
|
|
19717
19990
|
pathWithQuery: "/2/articles/draft",
|
|
19718
|
-
|
|
19991
|
+
session: options.session,
|
|
19719
19992
|
jsonBody: payload
|
|
19720
19993
|
});
|
|
19721
19994
|
if (resp.status >= 400) {
|
|
@@ -19736,10 +20009,10 @@ async function publishXArticle(options) {
|
|
|
19736
20009
|
if (!/^[0-9]{1,19}$/.test(cleanId)) {
|
|
19737
20010
|
throw new Error(`Invalid article_id "${options.articleId}": expected a numeric X snowflake ID.`);
|
|
19738
20011
|
}
|
|
19739
|
-
const resp = await
|
|
20012
|
+
const resp = await authorizedJsonRequest({
|
|
19740
20013
|
method: "POST",
|
|
19741
20014
|
pathWithQuery: `/2/articles/${encodeURIComponent(cleanId)}/publish`,
|
|
19742
|
-
|
|
20015
|
+
session: options.session
|
|
19743
20016
|
});
|
|
19744
20017
|
if (resp.status >= 400) {
|
|
19745
20018
|
throw new Error(`articlePublish failed (HTTP ${resp.status}): ${JSON.stringify(resp.data)}`);
|
|
@@ -19757,7 +20030,7 @@ async function publishXArticle(options) {
|
|
|
19757
20030
|
|
|
19758
20031
|
// src/server.ts
|
|
19759
20032
|
var PACKAGE_NAME = "@wezzard/mcp-x-articles";
|
|
19760
|
-
var PACKAGE_VERSION = "0.
|
|
20033
|
+
var PACKAGE_VERSION = "0.3.0";
|
|
19761
20034
|
var MAX_INLINE_PREVIEW_BYTES = 5 * 1024 * 1024;
|
|
19762
20035
|
var PREVIEWABLE_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
19763
20036
|
var SERVER_INSTRUCTIONS = [
|
|
@@ -19772,13 +20045,13 @@ var TOOLS = [
|
|
|
19772
20045
|
{
|
|
19773
20046
|
name: "x_article_auth_status",
|
|
19774
20047
|
title: "Check or Setup X Articles Authentication",
|
|
19775
|
-
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.",
|
|
19776
20049
|
inputSchema: {
|
|
19777
20050
|
type: "object",
|
|
19778
20051
|
properties: {
|
|
19779
20052
|
login: {
|
|
19780
20053
|
type: "boolean",
|
|
19781
|
-
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."
|
|
19782
20055
|
},
|
|
19783
20056
|
verify: {
|
|
19784
20057
|
type: "boolean",
|
|
@@ -19979,13 +20252,18 @@ function createMcpServer() {
|
|
|
19979
20252
|
const login = Boolean(args.login);
|
|
19980
20253
|
const verify = args.verify !== false;
|
|
19981
20254
|
const hostUi = detectHostConfigUi();
|
|
19982
|
-
const { credentials, source: credentialSource } =
|
|
20255
|
+
const { credentials, source: credentialSource } = loadOAuth2ClientCredentials();
|
|
19983
20256
|
if (!credentials) {
|
|
19984
20257
|
if (hostUi.hasNativeConfigUi || !login) {
|
|
19985
20258
|
return jsonToolResult({
|
|
20259
|
+
auth_mode: "oauth2",
|
|
19986
20260
|
configured: false,
|
|
19987
20261
|
credential_source: "none",
|
|
19988
20262
|
token_cached: false,
|
|
20263
|
+
has_refresh_token: false,
|
|
20264
|
+
access_token_expires_at: null,
|
|
20265
|
+
scopes: null,
|
|
20266
|
+
refreshed: false,
|
|
19989
20267
|
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
19990
20268
|
native_config_ui_url: hostUi.configUiUrl,
|
|
19991
20269
|
setup_hint: hostUi.setupInstruction
|
|
@@ -19993,16 +20271,21 @@ function createMcpServer() {
|
|
|
19993
20271
|
}
|
|
19994
20272
|
}
|
|
19995
20273
|
if (credentials) {
|
|
19996
|
-
const cached2 =
|
|
20274
|
+
const cached2 = loadOAuth2UserTokens(credentials.clientId);
|
|
19997
20275
|
if (!cached2.tokens && !login) {
|
|
19998
20276
|
return jsonToolResult({
|
|
20277
|
+
auth_mode: "oauth2",
|
|
19999
20278
|
configured: true,
|
|
20000
20279
|
credential_source: credentialSource,
|
|
20001
20280
|
token_cached: false,
|
|
20002
20281
|
token_source: "none",
|
|
20282
|
+
has_refresh_token: false,
|
|
20283
|
+
access_token_expires_at: null,
|
|
20284
|
+
scopes: null,
|
|
20285
|
+
refreshed: false,
|
|
20003
20286
|
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
20004
20287
|
native_config_ui_url: hostUi.configUiUrl,
|
|
20005
|
-
setup_hint: hostUi.hasNativeConfigUi ? `
|
|
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."
|
|
20006
20289
|
});
|
|
20007
20290
|
}
|
|
20008
20291
|
}
|
|
@@ -20011,10 +20294,15 @@ function createMcpServer() {
|
|
|
20011
20294
|
verifyProbe: verify
|
|
20012
20295
|
});
|
|
20013
20296
|
return jsonToolResult({
|
|
20297
|
+
auth_mode: "oauth2",
|
|
20014
20298
|
configured: true,
|
|
20015
20299
|
credential_source: session.credentialSource,
|
|
20016
20300
|
token_cached: true,
|
|
20017
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),
|
|
20018
20306
|
has_native_config_ui: hostUi.hasNativeConfigUi,
|
|
20019
20307
|
native_config_ui_url: hostUi.configUiUrl,
|
|
20020
20308
|
verified: verify,
|
|
@@ -20076,7 +20364,7 @@ function createMcpServer() {
|
|
|
20076
20364
|
if (includePreviews) {
|
|
20077
20365
|
for (const img of reviewImagePaths) {
|
|
20078
20366
|
if (img.is_remote || !existsSync3(img.resolved_path)) continue;
|
|
20079
|
-
const st2 =
|
|
20367
|
+
const st2 = statSync2(img.resolved_path);
|
|
20080
20368
|
if (!st2.isFile() || st2.size > MAX_INLINE_PREVIEW_BYTES) continue;
|
|
20081
20369
|
const mime = guessMediaType(img.resolved_path);
|
|
20082
20370
|
if (!PREVIEWABLE_MIMES.has(mime)) continue;
|
|
@@ -20141,8 +20429,8 @@ function createMcpServer() {
|
|
|
20141
20429
|
const up = await uploadMediaBuffer({
|
|
20142
20430
|
bytes: loaded.bytes,
|
|
20143
20431
|
mediaType: loaded.mediaType,
|
|
20144
|
-
mediaCategory:
|
|
20145
|
-
|
|
20432
|
+
mediaCategory: guessMediaCategory(loaded.mediaType),
|
|
20433
|
+
session,
|
|
20146
20434
|
label: src
|
|
20147
20435
|
});
|
|
20148
20436
|
mediaMap[src] = {
|
|
@@ -20162,7 +20450,7 @@ function createMcpServer() {
|
|
|
20162
20450
|
bytes: loadedCover.bytes,
|
|
20163
20451
|
mediaType: loadedCover.mediaType,
|
|
20164
20452
|
mediaCategory: "tweet_image",
|
|
20165
|
-
|
|
20453
|
+
session,
|
|
20166
20454
|
label: "cover_image"
|
|
20167
20455
|
});
|
|
20168
20456
|
coverMediaId = upCover.media_id;
|
|
@@ -20176,7 +20464,7 @@ function createMcpServer() {
|
|
|
20176
20464
|
contentState: finalConversion.content_state,
|
|
20177
20465
|
coverMediaId,
|
|
20178
20466
|
coverMediaCategory: "tweet_image",
|
|
20179
|
-
|
|
20467
|
+
session
|
|
20180
20468
|
});
|
|
20181
20469
|
return jsonToolResult({
|
|
20182
20470
|
ok: true,
|
|
@@ -20200,7 +20488,7 @@ function createMcpServer() {
|
|
|
20200
20488
|
});
|
|
20201
20489
|
const published = await publishXArticle({
|
|
20202
20490
|
articleId,
|
|
20203
|
-
|
|
20491
|
+
session,
|
|
20204
20492
|
usernameHint: session.user?.username
|
|
20205
20493
|
});
|
|
20206
20494
|
return jsonToolResult({
|
|
@@ -20236,8 +20524,8 @@ function printHelp() {
|
|
|
20236
20524
|
"",
|
|
20237
20525
|
"Usage:",
|
|
20238
20526
|
" mcp-x-articles Start the MCP server over stdio (default)",
|
|
20239
|
-
" mcp-x-articles auth Configure X OAuth
|
|
20240
|
-
" 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",
|
|
20241
20529
|
" mcp-x-articles --version Print package version",
|
|
20242
20530
|
" mcp-x-articles --help Print this help message",
|
|
20243
20531
|
""
|
|
@@ -20245,57 +20533,80 @@ function printHelp() {
|
|
|
20245
20533
|
);
|
|
20246
20534
|
}
|
|
20247
20535
|
async function runAuthCli(resetKeys) {
|
|
20248
|
-
let { credentials, source } =
|
|
20536
|
+
let { credentials, source } = loadOAuth2ClientCredentials();
|
|
20537
|
+
let cliRefreshToken = "";
|
|
20249
20538
|
if (!credentials || resetKeys) {
|
|
20250
20539
|
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
20251
20540
|
try {
|
|
20252
20541
|
process.stderr.write(
|
|
20253
|
-
"
|
|
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"
|
|
20254
20543
|
);
|
|
20255
|
-
const
|
|
20256
|
-
const
|
|
20257
|
-
|
|
20258
|
-
|
|
20259
|
-
|
|
20260
|
-
|
|
20261
|
-
|
|
20262
|
-
|
|
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}.
|
|
20263
20559
|
`);
|
|
20264
20560
|
} finally {
|
|
20265
20561
|
rl.close();
|
|
20266
20562
|
}
|
|
20267
20563
|
} else {
|
|
20268
|
-
process.stderr.write(`Using existing
|
|
20564
|
+
process.stderr.write(`Using existing OAuth 2.0 client credentials from ${source}.
|
|
20269
20565
|
`);
|
|
20270
20566
|
}
|
|
20271
|
-
|
|
20272
|
-
|
|
20273
|
-
|
|
20274
|
-
|
|
20275
|
-
|
|
20276
|
-
|
|
20277
|
-
|
|
20278
|
-
|
|
20279
|
-
|
|
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
|
+
}
|
|
20280
20587
|
const verified = await ensureAuthenticatedSession({
|
|
20281
20588
|
allowInteractiveLogin: false,
|
|
20282
20589
|
verifyProbe: true
|
|
20283
20590
|
});
|
|
20284
20591
|
const handle = verified.user?.username ? `@${verified.user.username}` : "authenticated account";
|
|
20285
20592
|
process.stdout.write(
|
|
20286
|
-
`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)}).
|
|
20287
20594
|
`
|
|
20288
20595
|
);
|
|
20289
20596
|
}
|
|
20290
20597
|
async function runStatusCli() {
|
|
20291
|
-
const { credentials, source } =
|
|
20598
|
+
const { credentials, source } = loadOAuth2ClientCredentials();
|
|
20292
20599
|
if (!credentials) {
|
|
20293
20600
|
process.stdout.write(
|
|
20294
20601
|
JSON.stringify(
|
|
20295
20602
|
{
|
|
20603
|
+
auth_mode: "oauth2",
|
|
20296
20604
|
configured: false,
|
|
20297
20605
|
credential_source: "none",
|
|
20298
20606
|
token_cached: false,
|
|
20607
|
+
has_refresh_token: false,
|
|
20608
|
+
access_token_expires_at: null,
|
|
20609
|
+
scopes: null,
|
|
20299
20610
|
hint: "Call x_article_auth_status({ login: true }) in your agent or run `npx @wezzard/mcp-x-articles auth`."
|
|
20300
20611
|
},
|
|
20301
20612
|
null,
|
|
@@ -20304,14 +20615,18 @@ async function runStatusCli() {
|
|
|
20304
20615
|
);
|
|
20305
20616
|
return;
|
|
20306
20617
|
}
|
|
20307
|
-
const tok =
|
|
20618
|
+
const tok = loadOAuth2UserTokens(credentials.clientId);
|
|
20308
20619
|
process.stdout.write(
|
|
20309
20620
|
JSON.stringify(
|
|
20310
20621
|
{
|
|
20622
|
+
auth_mode: "oauth2",
|
|
20311
20623
|
configured: true,
|
|
20312
20624
|
credential_source: source,
|
|
20313
20625
|
token_cached: Boolean(tok.tokens),
|
|
20314
|
-
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
|
|
20315
20630
|
},
|
|
20316
20631
|
null,
|
|
20317
20632
|
2
|
|
@@ -20359,29 +20674,41 @@ if (isDirectExecution()) {
|
|
|
20359
20674
|
}
|
|
20360
20675
|
export {
|
|
20361
20676
|
DEFAULT_KEYCHAIN_SERVICE,
|
|
20677
|
+
DEFAULT_OAUTH2_SCOPES,
|
|
20678
|
+
OAuth2TokenError,
|
|
20362
20679
|
PACKAGE_NAME,
|
|
20363
20680
|
PACKAGE_VERSION,
|
|
20364
20681
|
SERVER_INSTRUCTIONS,
|
|
20365
|
-
|
|
20366
|
-
|
|
20682
|
+
buildOAuth2AuthorizeUrl,
|
|
20683
|
+
clearOAuth2ClientCredentials,
|
|
20684
|
+
clearOAuth2UserTokens,
|
|
20685
|
+
clientKeyId,
|
|
20367
20686
|
computePreflightToken,
|
|
20368
20687
|
configDirPath,
|
|
20369
|
-
consumerKeyId,
|
|
20370
20688
|
convertMarkdownFile,
|
|
20371
20689
|
createMcpServer,
|
|
20372
20690
|
detectHostConfigUi,
|
|
20691
|
+
ensureAuthenticatedSession,
|
|
20692
|
+
exchangeAuthorizationCode,
|
|
20373
20693
|
extractMarkdownImageSrcs,
|
|
20694
|
+
generatePkcePair,
|
|
20695
|
+
getOAuth2AuthorizeUrl,
|
|
20696
|
+
getOAuth2Scopes,
|
|
20697
|
+
getOAuth2TokenUrl,
|
|
20698
|
+
guessMediaCategory,
|
|
20699
|
+
guessMediaType,
|
|
20374
20700
|
keychainServiceName,
|
|
20375
|
-
|
|
20376
|
-
|
|
20701
|
+
loadOAuth2ClientCredentials,
|
|
20702
|
+
loadOAuth2UserTokens,
|
|
20377
20703
|
markdownToContentState,
|
|
20704
|
+
refreshOAuth2Token,
|
|
20378
20705
|
resolveCoverImagePath,
|
|
20379
|
-
|
|
20380
|
-
|
|
20381
|
-
|
|
20382
|
-
saveUserOAuthTokens,
|
|
20706
|
+
runInteractiveSetupAndOAuth2Flow,
|
|
20707
|
+
saveOAuth2ClientCredentials,
|
|
20708
|
+
saveOAuth2UserTokens,
|
|
20383
20709
|
scanSensitiveFile,
|
|
20384
20710
|
scanText,
|
|
20385
|
-
|
|
20386
|
-
verifyPreflightToken
|
|
20711
|
+
sha256Hex,
|
|
20712
|
+
verifyPreflightToken,
|
|
20713
|
+
withOAuth2RefreshLock
|
|
20387
20714
|
};
|