linkedin-relay-mcp 1.0.0 → 1.1.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/README.md CHANGED
@@ -32,12 +32,29 @@ claude mcp add linkedin-relay -s user -- bun "$(npm root -g)/linkedin-relay-mcp/
32
32
  | `post` · `reactions` | a post's comment thread, and who engaged |
33
33
  | `sync` · `local` · `connections` · `my-posts` | fill a local cache, then query it for free |
34
34
  | `whoami` · `doctor` · `risk` · `budget` · `cache-status` | session, standing and spend |
35
- | `share` · `comment` · `react` | writes, over LinkedIn's official OAuth scope |
35
+ | `oauth` · `share` · `comment` · `react` | writes, over LinkedIn's official OAuth scope |
36
36
  | `purge` | delete cached data |
37
37
 
38
38
  Every command prints a JSON envelope on stdout. `--compact` and `--fields a,b` trim the output;
39
39
  `--raw` keeps the original Voyager node for when a shape has drifted.
40
40
 
41
+ ## Writing
42
+
43
+ Reads have no sanctioned path, so they go over Voyager and carry the risk below. Writes *do* have
44
+ one, so they don't get to spend the same currency: posting, commenting and reacting all go over
45
+ `w_member_social`, LinkedIn's own self-serve scope. It needs an app you register yourself — two
46
+ self-serve products, no partner review — and then:
47
+
48
+ ```bash
49
+ lnrelay oauth login --client-id <id> # opens consent, catches the callback, stores the token
50
+ lnrelay share "text" # prints the plan, asks, then posts
51
+ lnrelay oauth status | logout
52
+ ```
53
+
54
+ `lnrelay oauth login` with nothing set up prints the registration steps. Every write stops at an
55
+ interactive terminal and shows exactly what it will send, to whom, and how reversible it is — no
56
+ TTY means no write and no network call. There is no `--yes`.
57
+
41
58
  ## Design in one screen
42
59
 
43
60
  - **Browserless raw HTTP** to LinkedIn's Voyager API. A real browser mints cookies once, via CDP, and
@@ -88,7 +105,7 @@ position under argument. The convergence and the full disagreement record are in
88
105
  ## Development
89
106
 
90
107
  ```bash
91
- bun run check # typecheck + lint + 273 tests
108
+ bun run check # typecheck + lint + 317 tests
92
109
  bun run build
93
110
  bun run dev -- <command>
94
111
  ```
package/dist/cli.js CHANGED
@@ -1938,6 +1938,291 @@ function runDoctor(now, offline) {
1938
1938
  });
1939
1939
  }
1940
1940
 
1941
+ // src/commands/oauth.ts
1942
+ import { spawn } from "child_process";
1943
+ import { createServer } from "http";
1944
+ import { createInterface } from "readline/promises";
1945
+
1946
+ // src/engine/oauth.ts
1947
+ var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
1948
+ var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
1949
+ var USERINFO = "https://api.linkedin.com/v2/userinfo";
1950
+ var CALLBACK_PORT = 53682;
1951
+ var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
1952
+ var SCOPES = ["openid", "profile", "w_member_social"];
1953
+ function authorizationUrl(clientId, state) {
1954
+ const params = new URLSearchParams({
1955
+ response_type: "code",
1956
+ client_id: clientId,
1957
+ redirect_uri: REDIRECT_URI,
1958
+ state,
1959
+ scope: SCOPES.join(" ")
1960
+ });
1961
+ return `${AUTHORIZE}?${params.toString()}`;
1962
+ }
1963
+ async function exchange(code, config, deps) {
1964
+ const body = new URLSearchParams({
1965
+ grant_type: "authorization_code",
1966
+ code,
1967
+ redirect_uri: REDIRECT_URI,
1968
+ client_id: config.clientId,
1969
+ client_secret: config.clientSecret
1970
+ });
1971
+ let res;
1972
+ try {
1973
+ res = await deps.fetch(TOKEN, {
1974
+ method: "POST",
1975
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1976
+ body: body.toString()
1977
+ });
1978
+ } catch (e) {
1979
+ return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
1980
+ }
1981
+ const text2 = await res.text();
1982
+ if (res.status !== 200) {
1983
+ return {
1984
+ ok: false,
1985
+ message: `LinkedIn rejected the code exchange (${res.status})`,
1986
+ // The most common causes, in the order they actually happen.
1987
+ hint: `Check that the app has BOTH products added, and that its Auth tab lists exactly ${REDIRECT_URI} as an authorized redirect URL. Response: ${text2.slice(0, 200)}`
1988
+ };
1989
+ }
1990
+ let parsed;
1991
+ try {
1992
+ parsed = JSON.parse(text2);
1993
+ } catch {
1994
+ return { ok: false, message: "token response was not JSON" };
1995
+ }
1996
+ const accessToken = parsed.access_token;
1997
+ const expiresIn = parsed.expires_in;
1998
+ if (typeof accessToken !== "string" || accessToken === "") {
1999
+ return { ok: false, message: "token response carried no access_token" };
2000
+ }
2001
+ const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
2002
+ return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
2003
+ }
2004
+ async function fetchMemberUrn(accessToken, deps) {
2005
+ let res;
2006
+ try {
2007
+ res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
2008
+ } catch (e) {
2009
+ return { ok: false, message: `could not reach userinfo: ${e.message}` };
2010
+ }
2011
+ if (res.status !== 200) {
2012
+ return {
2013
+ ok: false,
2014
+ message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
2015
+ };
2016
+ }
2017
+ const parsed = await res.json();
2018
+ if (typeof parsed.sub !== "string" || parsed.sub === "") {
2019
+ return { ok: false, message: "userinfo carried no subject claim" };
2020
+ }
2021
+ return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
2022
+ }
2023
+ function parseCallback(rawUrl, expectedState) {
2024
+ let url;
2025
+ try {
2026
+ url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
2027
+ } catch {
2028
+ return { ok: false, message: "callback URL was unparseable" };
2029
+ }
2030
+ const error = url.searchParams.get("error");
2031
+ if (error !== null) {
2032
+ const description = url.searchParams.get("error_description") ?? "";
2033
+ return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
2034
+ }
2035
+ const state = url.searchParams.get("state");
2036
+ if (state !== expectedState) {
2037
+ return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
2038
+ }
2039
+ const code = url.searchParams.get("code");
2040
+ if (code === null || code === "") return { ok: false, message: "callback carried no code" };
2041
+ return { ok: true, code };
2042
+ }
2043
+
2044
+ // src/commands/token.ts
2045
+ init_store();
2046
+ import { existsSync as existsSync3, rmSync } from "fs";
2047
+ var TOKEN_FILE = "oauth.json";
2048
+ var OAUTH_SETUP = [
2049
+ "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
2050
+ "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
2051
+ "cannot be created on your behalf.",
2052
+ "",
2053
+ " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
2054
+ ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
2055
+ " Both are self-serve: no partner review, no verification, no screencast.",
2056
+ ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
2057
+ " 4. Run: lnrelay oauth login --client-id <id>",
2058
+ " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
2059
+ ].join("\n");
2060
+ function tokenPath() {
2061
+ return cachePath(TOKEN_FILE);
2062
+ }
2063
+ function loadToken() {
2064
+ const result = loadJson(tokenPath());
2065
+ return result.state === "ok" ? result.value : null;
2066
+ }
2067
+ function saveToken(token) {
2068
+ saveJson(tokenPath(), token);
2069
+ }
2070
+ function deleteToken() {
2071
+ const path = tokenPath();
2072
+ if (!existsSync3(path)) return false;
2073
+ rmSync(path, { force: true });
2074
+ return true;
2075
+ }
2076
+
2077
+ // src/commands/oauth.ts
2078
+ var CALLBACK_TIMEOUT_MS = 3e5;
2079
+ var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
2080
+ <body style="font:16px system-ui;padding:3rem;max-width:32rem">
2081
+ <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
2082
+ function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
2083
+ return new Promise((ready) => {
2084
+ let settle = () => {
2085
+ };
2086
+ const code = new Promise((r) => {
2087
+ settle = r;
2088
+ });
2089
+ const server = createServer((req, res) => {
2090
+ const url = req.url ?? "/";
2091
+ if (!url.startsWith("/callback")) {
2092
+ res.writeHead(404, { connection: "close" });
2093
+ res.end();
2094
+ return;
2095
+ }
2096
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
2097
+ res.end(DONE_PAGE);
2098
+ settle(parseCallback(url, state));
2099
+ });
2100
+ const timer = setTimeout(() => {
2101
+ settle({
2102
+ ok: false,
2103
+ message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
2104
+ });
2105
+ }, timeoutMs);
2106
+ timer.unref?.();
2107
+ const close = () => {
2108
+ clearTimeout(timer);
2109
+ server.closeAllConnections?.();
2110
+ server.close();
2111
+ };
2112
+ server.once("error", (e) => {
2113
+ clearTimeout(timer);
2114
+ const why = e.code === "EADDRINUSE" ? `port ${CALLBACK_PORT} is already in use \u2014 close whatever holds it and retry` : `could not open the callback listener: ${e.message}`;
2115
+ ready({ ok: false, message: why });
2116
+ });
2117
+ server.listen(CALLBACK_PORT, "127.0.0.1", () => {
2118
+ ready({ ok: true, code, close });
2119
+ });
2120
+ });
2121
+ }
2122
+ function openBrowser(url) {
2123
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2124
+ try {
2125
+ spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
2126
+ } catch {
2127
+ }
2128
+ }
2129
+ function loginDeps() {
2130
+ return {
2131
+ state: () => crypto.randomUUID(),
2132
+ listen: (state) => listenForCallback(state),
2133
+ open: openBrowser,
2134
+ write: (s) => process.stderr.write(s),
2135
+ isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
2136
+ prompt: async (question) => {
2137
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2138
+ const answer = await rl.question(question);
2139
+ rl.close();
2140
+ return answer;
2141
+ },
2142
+ now: Date.now,
2143
+ fetch: globalThis.fetch
2144
+ };
2145
+ }
2146
+ async function credentials(opts, deps) {
2147
+ const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
2148
+ if (clientId === void 0 || clientId === "") {
2149
+ return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
2150
+ }
2151
+ let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
2152
+ if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
2153
+ clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
2154
+ }
2155
+ if (clientSecret === void 0 || clientSecret === "") {
2156
+ return err(
2157
+ "oauth",
2158
+ "INVALID_INPUT",
2159
+ "a client secret is required, and there is no terminal to ask on",
2160
+ `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
2161
+
2162
+ ${OAUTH_SETUP}`
2163
+ );
2164
+ }
2165
+ return { clientId, clientSecret };
2166
+ }
2167
+ async function runOauthLogin(opts, deps = loginDeps()) {
2168
+ const creds = await credentials(opts, deps);
2169
+ if ("ok" in creds) return creds;
2170
+ const state = deps.state();
2171
+ const listener = await deps.listen(state);
2172
+ if (!listener.ok) {
2173
+ return err("oauth", "AUTH_FAILED", listener.message);
2174
+ }
2175
+ try {
2176
+ const url = authorizationUrl(creds.clientId, state);
2177
+ deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
2178
+
2179
+ ${url}
2180
+
2181
+ `);
2182
+ deps.open(url);
2183
+ const callback = await listener.code;
2184
+ if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
2185
+ const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
2186
+ if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
2187
+ const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
2188
+ if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
2189
+ saveToken({
2190
+ accessToken: token.accessToken,
2191
+ memberUrn: member.memberUrn,
2192
+ expiresAt: token.expiresAt
2193
+ });
2194
+ return ok("oauth", {
2195
+ memberUrn: member.memberUrn,
2196
+ scopes: SCOPES,
2197
+ expiresAt: new Date(token.expiresAt).toISOString(),
2198
+ storedAt: tokenPath(),
2199
+ // Refresh tokens are partner-gated, so renewal is re-running this.
2200
+ renewal: "run `lnrelay oauth login` again when it expires"
2201
+ });
2202
+ } finally {
2203
+ listener.close();
2204
+ }
2205
+ }
2206
+ function runOauthLogout() {
2207
+ const removed = deleteToken();
2208
+ return ok("oauth", {
2209
+ removed,
2210
+ note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
2211
+ });
2212
+ }
2213
+ function runOauthStatus() {
2214
+ const token = loadToken();
2215
+ if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
2216
+ return ok("oauth", {
2217
+ memberUrn: token.memberUrn,
2218
+ expiresAt: new Date(token.expiresAt).toISOString(),
2219
+ expired: token.expiresAt <= Date.now(),
2220
+ scopes: SCOPES,
2221
+ storedAt: tokenPath(),
2222
+ writeCap: CAPS.write.perDay
2223
+ });
2224
+ }
2225
+
1941
2226
  // src/commands/registry.ts
1942
2227
  var COMMANDS = [
1943
2228
  // ─── local / meta — no network, available today ────────────────────────────
@@ -2110,8 +2395,8 @@ var COMMANDS = [
2110
2395
  {
2111
2396
  name: "oauth",
2112
2397
  cost: "free",
2113
- summary: "OAuth token status for writes. Never prints the token.",
2114
- usage: "lnrelay oauth",
2398
+ summary: "Obtain and inspect the write credential, over LinkedIn's own self-serve scope. Never prints the token.",
2399
+ usage: "lnrelay oauth login --client-id <id> [--client-secret <secret>]\n lnrelay oauth status | logout\n The secret is prompted for if omitted; LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET also work.\n Needs an app you registered: see the hint printed when no token is stored.",
2115
2400
  audience: ["cli"],
2116
2401
  risk: "local",
2117
2402
  implemented: true
@@ -2277,7 +2562,7 @@ async function runSync(source, limit, force, now = Date.now()) {
2277
2562
 
2278
2563
  // src/commands/write.ts
2279
2564
  init_store();
2280
- import { createInterface } from "readline/promises";
2565
+ import { createInterface as createInterface2 } from "readline/promises";
2281
2566
 
2282
2567
  // src/engine/oauth-write.ts
2283
2568
  var API = "https://api.linkedin.com";
@@ -2436,22 +2721,6 @@ async function confirmWrite(plan, budgetLine2, deps) {
2436
2721
  }
2437
2722
 
2438
2723
  // src/commands/write.ts
2439
- var TOKEN_FILE = "oauth.json";
2440
- var OAUTH_SETUP = [
2441
- "No OAuth token stored. Writes go over LinkedIn's OWN self-serve scope rather than the private",
2442
- "API, which is the one legitimacy wedge an individual actually has \u2014 but the app has to be",
2443
- "registered by you; it cannot be created on your behalf.",
2444
- "",
2445
- " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
2446
- ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
2447
- " Both are self-serve: no partner review, no verification, no screencast.",
2448
- " 3. Auth tab \u2192 add redirect URL http://localhost:53682/callback",
2449
- " 4. Run: lnrelay oauth --client-id <id> --client-secret <secret>"
2450
- ].join("\n");
2451
- function loadToken() {
2452
- const result = loadJson(cachePath(TOKEN_FILE));
2453
- return result.state === "ok" ? result.value : null;
2454
- }
2455
2724
  function ledger() {
2456
2725
  const result = loadJson(cachePath("budget.json"));
2457
2726
  return result.state === "ok" ? result.value : emptyLedger();
@@ -2464,7 +2733,7 @@ function terminalDeps() {
2464
2733
  return {
2465
2734
  isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,
2466
2735
  prompt: async (question) => {
2467
- const rl = createInterface({ input: process.stdin, output: process.stderr });
2736
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
2468
2737
  const answer = await rl.question(question);
2469
2738
  rl.close();
2470
2739
  return answer;
@@ -2475,7 +2744,14 @@ function terminalDeps() {
2475
2744
  function prepare(command, now) {
2476
2745
  const token = loadToken();
2477
2746
  if (token === null) {
2478
- return err(command, "AUTH_FAILED", "no OAuth token \u2014 writes need one", OAUTH_SETUP);
2747
+ return err(
2748
+ command,
2749
+ "AUTH_FAILED",
2750
+ "no OAuth token \u2014 writes need one",
2751
+ `Run \`lnrelay oauth login --client-id <id>\` first.
2752
+
2753
+ ${OAUTH_SETUP}`
2754
+ );
2479
2755
  }
2480
2756
  const attempt = spend(ledger(), "write", now);
2481
2757
  if ("error" in attempt) {
@@ -2574,17 +2850,6 @@ async function runReact(postUrn, type, now = Date.now(), deps = terminalDeps())
2574
2850
  });
2575
2851
  return result.ok ? ok("react", { id: result.id }) : err("react", result.code, result.message, result.hint);
2576
2852
  }
2577
- function runOauthStatus() {
2578
- const token = loadToken();
2579
- if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
2580
- return ok("oauth", {
2581
- memberUrn: token.memberUrn,
2582
- expiresAt: new Date(token.expiresAt).toISOString(),
2583
- expired: token.expiresAt <= Date.now(),
2584
- scope: "w_member_social",
2585
- writeCap: CAPS.write.perDay
2586
- });
2587
- }
2588
2853
 
2589
2854
  // src/entry.ts
2590
2855
  import { realpathSync } from "fs";
@@ -2629,6 +2894,25 @@ function output(args) {
2629
2894
  if (fields !== void 0) opts.fields = fields;
2630
2895
  return opts;
2631
2896
  }
2897
+ async function oauth(args) {
2898
+ const sub = args.positionals[0] ?? "status";
2899
+ if (sub === "status") return runOauthStatus();
2900
+ if (sub === "logout") return runOauthLogout();
2901
+ if (sub === "login") {
2902
+ const opts = {};
2903
+ const id = str(args, "client-id");
2904
+ const secret = str(args, "client-secret");
2905
+ if (id !== void 0) opts.clientId = id;
2906
+ if (secret !== void 0) opts.clientSecret = secret;
2907
+ return runOauthLogin(opts);
2908
+ }
2909
+ return err(
2910
+ "oauth",
2911
+ "INVALID_INPUT",
2912
+ `unknown oauth subcommand '${sub}'`,
2913
+ "one of: login, status, logout"
2914
+ );
2915
+ }
2632
2916
  async function dispatch(argv, now) {
2633
2917
  const args = parseArgs(argv);
2634
2918
  const { command } = args;
@@ -2695,7 +2979,7 @@ async function dispatch(argv, now) {
2695
2979
  case "login":
2696
2980
  return runLogin();
2697
2981
  case "oauth":
2698
- return runOauthStatus();
2982
+ return oauth(args);
2699
2983
  case "share":
2700
2984
  return runShare(args.positionals[0], str(args, "visibility") ?? "public", now);
2701
2985
  case "comment":