linkedin-relay-mcp 1.0.0 → 1.2.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/dist/cli.js CHANGED
@@ -1,13 +1,53 @@
1
1
  #!/usr/bin/env bun
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res) => function __init() {
5
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
- };
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
2
+ // src/args.ts
3
+ function parseArgs(argv) {
4
+ const [command, ...rest] = argv;
5
+ const positionals = [];
6
+ const flags = {};
7
+ for (let i = 0; i < rest.length; i++) {
8
+ const token = rest[i];
9
+ if (token === void 0) continue;
10
+ if (token.startsWith("--")) {
11
+ const key = token.slice(2);
12
+ const next = rest[i + 1];
13
+ if (next !== void 0 && !next.startsWith("--")) {
14
+ flags[key] = next;
15
+ i++;
16
+ } else {
17
+ flags[key] = true;
18
+ }
19
+ } else if (token.startsWith("-") && token.length > 1) {
20
+ const key = token.slice(1);
21
+ const next = rest[i + 1];
22
+ if (next !== void 0 && !next.startsWith("-")) {
23
+ flags[key] = next;
24
+ i++;
25
+ } else {
26
+ flags[key] = true;
27
+ }
28
+ } else {
29
+ positionals.push(token);
30
+ }
31
+ }
32
+ return { command, positionals, flags };
33
+ }
34
+ function bool(args, name) {
35
+ return args.flags[name] === true || args.flags[name] === "true";
36
+ }
37
+ function str(args, name) {
38
+ const v = args.flags[name];
39
+ return typeof v === "string" ? v : void 0;
40
+ }
41
+ function num(args, name) {
42
+ const v = str(args, name);
43
+ if (v === void 0) return void 0;
44
+ const n = Number(v);
45
+ return Number.isFinite(n) ? n : void 0;
46
+ }
47
+
48
+ // src/cache/db.ts
49
+ import { Database } from "bun:sqlite";
50
+ import { mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
11
51
 
12
52
  // src/cache/store.ts
13
53
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
@@ -49,34 +89,46 @@ function saveJson(path, value) {
49
89
  writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 384 });
50
90
  renameSync(tmp, path);
51
91
  }
52
- var init_store = __esm({
53
- "src/cache/store.ts"() {
54
- "use strict";
55
- }
56
- });
57
92
 
58
93
  // src/cache/db.ts
59
- var db_exports = {};
60
- __export(db_exports, {
61
- CacheCorrupt: () => CacheCorrupt,
62
- THIRD_PARTY_TTL_MS: () => THIRD_PARTY_TTL_MS,
63
- count: () => count,
64
- fold: () => fold,
65
- getCheckpoint: () => getCheckpoint,
66
- openDb: () => openDb,
67
- purge: () => purge,
68
- removeUrns: () => removeUrns,
69
- search: () => search,
70
- setCheckpoint: () => setCheckpoint,
71
- sweepExpired: () => sweepExpired,
72
- upsert: () => upsert,
73
- urnsFor: () => urnsFor
74
- });
75
- import { Database } from "bun:sqlite";
76
- import { mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
94
+ var DB_FILE = "cache.db";
95
+ var THIRD_PARTY_TTL_MS = 30 * 864e5;
77
96
  function fold(value) {
78
97
  return value.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
79
98
  }
99
+ var TABLES = [
100
+ `CREATE TABLE IF NOT EXISTS records (
101
+ urn TEXT NOT NULL,
102
+ source TEXT NOT NULL,
103
+ body TEXT,
104
+ text TEXT NOT NULL DEFAULT '',
105
+ textFold TEXT NOT NULL DEFAULT '',
106
+ firstSeenAt INTEGER NOT NULL,
107
+ updatedAt INTEGER NOT NULL,
108
+ expiresAt INTEGER,
109
+ PRIMARY KEY (urn, source)
110
+ )`,
111
+ `CREATE TABLE IF NOT EXISTS checkpoints (
112
+ source TEXT PRIMARY KEY,
113
+ lastSuccessfulAt INTEGER NOT NULL,
114
+ newestCreatedAt INTEGER,
115
+ headIds TEXT NOT NULL DEFAULT '[]',
116
+ state TEXT NOT NULL DEFAULT 'ok'
117
+ )`
118
+ ];
119
+ var INDEXES = [
120
+ "CREATE INDEX IF NOT EXISTS records_source ON records(source)",
121
+ "CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)",
122
+ "CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)"
123
+ ];
124
+ var CacheCorrupt = class extends Error {
125
+ constructor(message, quarantinedTo) {
126
+ super(message);
127
+ this.quarantinedTo = quarantinedTo;
128
+ this.name = "CacheCorrupt";
129
+ }
130
+ quarantinedTo;
131
+ };
80
132
  function openDb(now = Date.now()) {
81
133
  mkdirSync2(cacheDir(), { recursive: true });
82
134
  const path = cachePath(DB_FILE);
@@ -216,97 +268,6 @@ function purge(db, scope) {
216
268
  if (scope === "all") db.run("DELETE FROM checkpoints");
217
269
  return result.changes;
218
270
  }
219
- var DB_FILE, THIRD_PARTY_TTL_MS, TABLES, INDEXES, CacheCorrupt;
220
- var init_db = __esm({
221
- "src/cache/db.ts"() {
222
- "use strict";
223
- init_store();
224
- DB_FILE = "cache.db";
225
- THIRD_PARTY_TTL_MS = 30 * 864e5;
226
- TABLES = [
227
- `CREATE TABLE IF NOT EXISTS records (
228
- urn TEXT NOT NULL,
229
- source TEXT NOT NULL,
230
- body TEXT,
231
- text TEXT NOT NULL DEFAULT '',
232
- textFold TEXT NOT NULL DEFAULT '',
233
- firstSeenAt INTEGER NOT NULL,
234
- updatedAt INTEGER NOT NULL,
235
- expiresAt INTEGER,
236
- PRIMARY KEY (urn, source)
237
- )`,
238
- `CREATE TABLE IF NOT EXISTS checkpoints (
239
- source TEXT PRIMARY KEY,
240
- lastSuccessfulAt INTEGER NOT NULL,
241
- newestCreatedAt INTEGER,
242
- headIds TEXT NOT NULL DEFAULT '[]',
243
- state TEXT NOT NULL DEFAULT 'ok'
244
- )`
245
- ];
246
- INDEXES = [
247
- "CREATE INDEX IF NOT EXISTS records_source ON records(source)",
248
- "CREATE INDEX IF NOT EXISTS records_fold ON records(textFold)",
249
- "CREATE INDEX IF NOT EXISTS records_expires ON records(expiresAt)"
250
- ];
251
- CacheCorrupt = class extends Error {
252
- constructor(message, quarantinedTo) {
253
- super(message);
254
- this.quarantinedTo = quarantinedTo;
255
- this.name = "CacheCorrupt";
256
- }
257
- quarantinedTo;
258
- };
259
- }
260
- });
261
-
262
- // src/args.ts
263
- function parseArgs(argv) {
264
- const [command, ...rest] = argv;
265
- const positionals = [];
266
- const flags = {};
267
- for (let i = 0; i < rest.length; i++) {
268
- const token = rest[i];
269
- if (token === void 0) continue;
270
- if (token.startsWith("--")) {
271
- const key = token.slice(2);
272
- const next = rest[i + 1];
273
- if (next !== void 0 && !next.startsWith("--")) {
274
- flags[key] = next;
275
- i++;
276
- } else {
277
- flags[key] = true;
278
- }
279
- } else if (token.startsWith("-") && token.length > 1) {
280
- const key = token.slice(1);
281
- const next = rest[i + 1];
282
- if (next !== void 0 && !next.startsWith("-")) {
283
- flags[key] = next;
284
- i++;
285
- } else {
286
- flags[key] = true;
287
- }
288
- } else {
289
- positionals.push(token);
290
- }
291
- }
292
- return { command, positionals, flags };
293
- }
294
- function bool(args, name) {
295
- return args.flags[name] === true || args.flags[name] === "true";
296
- }
297
- function str(args, name) {
298
- const v = args.flags[name];
299
- return typeof v === "string" ? v : void 0;
300
- }
301
- function num(args, name) {
302
- const v = str(args, name);
303
- if (v === void 0) return void 0;
304
- const n = Number(v);
305
- return Number.isFinite(n) ? n : void 0;
306
- }
307
-
308
- // src/commands/cache.ts
309
- init_db();
310
271
 
311
272
  // src/engine/restli.ts
312
273
  var ENCODED = {
@@ -728,9 +689,6 @@ function retain(source, items) {
728
689
  }
729
690
  }
730
691
 
731
- // src/engine/index.ts
732
- init_store();
733
-
734
692
  // src/progress.ts
735
693
  function progressReporter(quiet, write = (s) => {
736
694
  process.stderr.write(s);
@@ -1021,10 +979,13 @@ function createClient(session, deps) {
1021
979
  return { request };
1022
980
  }
1023
981
  async function fetchRaw(spec, session, deps) {
982
+ const requestHeaders = buildHeaders(session);
983
+ if (spec.body !== void 0) requestHeaders["content-type"] = "application/json; charset=UTF-8";
1024
984
  try {
1025
985
  const res = await deps.fetch(spec.url, {
1026
986
  method: spec.method ?? "GET",
1027
- headers: buildHeaders(session),
987
+ headers: requestHeaders,
988
+ ...spec.body === void 0 ? {} : { body: JSON.stringify(spec.body) },
1028
989
  // Manual, so a login or checkpoint redirect is classified rather than
1029
990
  // silently followed into an HTML page that parses as "no data".
1030
991
  redirect: "manual"
@@ -1369,8 +1330,8 @@ function missingContract(name) {
1369
1330
  hint: "Only endpoints that returned 200 on this machine may back a command. Capture it with `bun run scripts/observe.ts`, verify it, then mark it verified in src/engine/contracts.ts."
1370
1331
  };
1371
1332
  }
1372
- function createEngine(session, deps, quiet = false) {
1373
- const client = createClient(session, {
1333
+ function createLiveClient(session, deps, quiet = false) {
1334
+ return createClient(session, {
1374
1335
  fetch: globalThis.fetch,
1375
1336
  // stdout stays JSON-only; progress is human chatter and goes to stderr.
1376
1337
  progress: progressReporter(quiet),
@@ -1389,6 +1350,9 @@ function createEngine(session, deps, quiet = false) {
1389
1350
  saveCooldown: (c) => saveJson(cachePath("cooldown.json"), c),
1390
1351
  ...deps
1391
1352
  });
1353
+ }
1354
+ function createEngine(session, deps, quiet = false) {
1355
+ const client = createLiveClient(session, deps, quiet);
1392
1356
  return {
1393
1357
  async whoami() {
1394
1358
  const contract = contractFor("me");
@@ -1568,7 +1532,6 @@ function totalResultCount(json) {
1568
1532
  }
1569
1533
 
1570
1534
  // src/engine/session.ts
1571
- init_store();
1572
1535
  var SESSION_FILE = "session.json";
1573
1536
  function loadSession() {
1574
1537
  const result = loadJson(cachePath(SESSION_FILE));
@@ -1654,6 +1617,247 @@ function getAllCookies(wsUrl) {
1654
1617
  });
1655
1618
  }
1656
1619
 
1620
+ // src/engine/voyager-write.ts
1621
+ var VOYAGER2 = "https://www.linkedin.com/voyager/api";
1622
+ var SHARE_URL = `${VOYAGER2}/contentcreation/normShares`;
1623
+ function sharePayload(text2, visibility) {
1624
+ return {
1625
+ visibleToConnectionsOnly: visibility === "CONNECTIONS",
1626
+ externalAudienceProviders: [],
1627
+ commentaryV2: { text: text2, attributes: [] },
1628
+ origin: "FEED",
1629
+ allowedCommentersScope: "ALL",
1630
+ postState: "PUBLISHED",
1631
+ media: []
1632
+ };
1633
+ }
1634
+ var POST_URN = /urn:li:(share|activity|ugcPost):\d+/;
1635
+ function isDeletableUrn(urn) {
1636
+ return new RegExp(`^${POST_URN.source}$`).test(urn);
1637
+ }
1638
+ function deleteUrl(urn) {
1639
+ return `${SHARE_URL}/${encodeURIComponent(urn)}`;
1640
+ }
1641
+ async function deletePost(confirmed, client) {
1642
+ const { urn } = confirmed.payload;
1643
+ const result = await client.request({
1644
+ url: deleteUrl(urn),
1645
+ method: "DELETE",
1646
+ spendClass: "write",
1647
+ operation: "delete"
1648
+ });
1649
+ if (result.ok) return { ok: true, id: urn };
1650
+ const notFound = result.code === "NOT_FOUND";
1651
+ const out = {
1652
+ ok: false,
1653
+ code: result.code,
1654
+ message: result.message
1655
+ };
1656
+ if (notFound) {
1657
+ out.hint = "Either the post is already gone \u2014 in which case nothing more is needed \u2014 or this is the wrong urn namespace for this endpoint. It is documented against `urn:li:share:<id>`; if you passed an activity or ugcPost urn, the same numeric id under `urn:li:share:` is the thing to try next.";
1658
+ } else if (result.hint !== void 0) {
1659
+ out.hint = result.hint;
1660
+ }
1661
+ return out;
1662
+ }
1663
+ function extractShareUrn(json) {
1664
+ return JSON.stringify(json ?? null).match(POST_URN)?.[0] ?? null;
1665
+ }
1666
+ async function share(confirmed, client) {
1667
+ const body = sharePayload(confirmed.payload.text, confirmed.payload.visibility);
1668
+ const result = await client.request({
1669
+ url: SHARE_URL,
1670
+ method: "POST",
1671
+ body,
1672
+ spendClass: "write",
1673
+ operation: "share"
1674
+ });
1675
+ if (!result.ok) {
1676
+ const out = { ok: false, code: result.code, message: result.message };
1677
+ if (result.hint !== void 0) out.hint = result.hint;
1678
+ return out;
1679
+ }
1680
+ const id = extractShareUrn(result.json);
1681
+ return id === null ? {
1682
+ ok: true,
1683
+ id: null,
1684
+ note: "LinkedIn accepted the post but the response carried no recognisable urn. Run `lnrelay sync my-posts && lnrelay my-posts` to confirm what actually landed \u2014 and do NOT re-run this command on the assumption it failed, or you will post twice."
1685
+ } : { ok: true, id };
1686
+ }
1687
+
1688
+ // src/commands/gate.ts
1689
+ import { createInterface } from "readline/promises";
1690
+
1691
+ // src/commands/confirm.ts
1692
+ import { createHash } from "crypto";
1693
+ function confirmToken(action, payload) {
1694
+ return createHash("sha256").update(`${action}:${JSON.stringify(payload)}`).digest("hex").slice(0, 4);
1695
+ }
1696
+ function riskLines(transport) {
1697
+ return transport === "oauth" ? [
1698
+ " This write itself is sanctioned \u2014 it uses LinkedIn's own",
1699
+ " w_member_social scope. The reads this tool performs are not."
1700
+ ] : [
1701
+ " This goes over the PRIVATE API, not a sanctioned one. It breaches",
1702
+ " LinkedIn User Agreement \xA78.2 and can permanently restrict this account."
1703
+ ];
1704
+ }
1705
+ function renderPlan(plan, budgetLine2) {
1706
+ const token = confirmToken(plan.action, plan.payload);
1707
+ const lines = [
1708
+ "",
1709
+ ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
1710
+ ` ${"\u2500".repeat(58)}`,
1711
+ ...plan.summary.map((l) => ` ${l}`),
1712
+ ` via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
1713
+ ` undo ${plan.reversibility}`,
1714
+ "",
1715
+ ...riskLines(plan.transport),
1716
+ ` ${budgetLine2}`,
1717
+ "",
1718
+ ` Type ${token} to confirm, anything else to abort: `
1719
+ ];
1720
+ return lines.join("\n");
1721
+ }
1722
+ async function confirmWrite(plan, budgetLine2, deps) {
1723
+ if (!deps.isTty) {
1724
+ return {
1725
+ ok: false,
1726
+ code: "CONFIRMATION_REQUIRED",
1727
+ message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,
1728
+ hint: "No terminal is attached, so nothing was sent and no network call was made. Run this command yourself in a shell. There is deliberately no --yes flag: an agent that could set one would not be confirming anything."
1729
+ };
1730
+ }
1731
+ const token = confirmToken(plan.action, plan.payload);
1732
+ const answer = (await deps.prompt(renderPlan(plan, budgetLine2))).trim();
1733
+ if (answer !== token) {
1734
+ return {
1735
+ ok: false,
1736
+ code: "CONFIRMATION_REQUIRED",
1737
+ message: "aborted \u2014 the confirmation token did not match",
1738
+ hint: "Nothing was sent. Re-run and type the token shown in the prompt."
1739
+ };
1740
+ }
1741
+ return {
1742
+ ok: true,
1743
+ confirmed: { action: plan.action, payload: plan.payload, token }
1744
+ };
1745
+ }
1746
+
1747
+ // src/commands/gate.ts
1748
+ function ledger() {
1749
+ const result = loadJson(cachePath("budget.json"));
1750
+ return result.state === "ok" ? result.value : emptyLedger();
1751
+ }
1752
+ function budgetLine(now) {
1753
+ const s = summarise(ledger(), "write", now);
1754
+ return `${s.remaining} of ${s.cap} writes left today.`;
1755
+ }
1756
+ function terminalDeps() {
1757
+ return {
1758
+ isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,
1759
+ prompt: async (question) => {
1760
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
1761
+ const answer = await rl.question(question);
1762
+ rl.close();
1763
+ return answer;
1764
+ },
1765
+ write: (s) => process.stderr.write(s)
1766
+ };
1767
+ }
1768
+ function reserve(command, now) {
1769
+ const attempt = spend(ledger(), "write", now);
1770
+ return "error" in attempt ? err(command, attempt.error.code, attempt.error.message, attempt.error.hint) : null;
1771
+ }
1772
+ async function gateWrite(command, plan, now, deps) {
1773
+ const outcome = await confirmWrite(plan, budgetLine(now), deps);
1774
+ if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);
1775
+ const attempt = spend(ledger(), "write", now);
1776
+ if ("permit" in attempt) saveJson(cachePath("budget.json"), attempt.ledger);
1777
+ return { confirmed: outcome.confirmed, payload: plan.payload };
1778
+ }
1779
+
1780
+ // src/commands/delete.ts
1781
+ var LOOKUP_LIMIT = 50;
1782
+ var PREVIEW_CHARS = 200;
1783
+ function postId(urn) {
1784
+ return /:(\d+)$/.exec(urn)?.[1];
1785
+ }
1786
+ function findOwnPost(posts, urn) {
1787
+ const id = postId(urn);
1788
+ if (id === void 0) return void 0;
1789
+ return posts.find((p) => typeof p.urn === "string" && postId(p.urn) === id);
1790
+ }
1791
+ function previewLines(post) {
1792
+ if (post === void 0) {
1793
+ return [
1794
+ "content COULD NOT READ THIS POST.",
1795
+ " It is not among your recent posts. That may only mean it is older",
1796
+ " than the page fetched \u2014 but nothing here has verified what you are",
1797
+ " about to delete, or that it is yours."
1798
+ ];
1799
+ }
1800
+ const text2 = typeof post.text === "string" ? post.text : "(no text \u2014 media-only post?)";
1801
+ const shown = text2.length > PREVIEW_CHARS ? `${text2.slice(0, PREVIEW_CHARS)}\u2026` : text2;
1802
+ return [`content "${shown.replace(/\n/g, " ")}"`];
1803
+ }
1804
+ async function lookup(urn, quiet) {
1805
+ const session = loadSession();
1806
+ if (session.state !== "ok") return void 0;
1807
+ const engine = createEngine(session.session, void 0, quiet);
1808
+ const me = await engine.whoami();
1809
+ if (!me.ok) return void 0;
1810
+ const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
1811
+ if (profileUrn === void 0) return void 0;
1812
+ const posts = await engine.myPosts(profileUrn, LOOKUP_LIMIT);
1813
+ if (!posts.ok) return void 0;
1814
+ return findOwnPost(shapeAll(posts.value.parsed.items, posts.value.index), urn);
1815
+ }
1816
+ async function runDelete(urn, now = Date.now(), deps, quiet = false) {
1817
+ if (urn === void 0 || urn === "") {
1818
+ return err(
1819
+ "delete",
1820
+ "INVALID_INPUT",
1821
+ "a post urn is required",
1822
+ "lnrelay delete <urn:li:share:\u2026 | urn:li:activity:\u2026>"
1823
+ );
1824
+ }
1825
+ if (!isDeletableUrn(urn)) {
1826
+ return err(
1827
+ "delete",
1828
+ "INVALID_INPUT",
1829
+ `'${urn}' does not identify a post`,
1830
+ "Expected urn:li:share:<id>, urn:li:activity:<id> or urn:li:ugcPost:<id>. Refusing before encoding it, because a well-formed request naming the wrong kind of entity is a request to destroy the wrong kind of thing."
1831
+ );
1832
+ }
1833
+ const session = loadSession();
1834
+ if (session.state === "corrupt") {
1835
+ return err("delete", "CACHE_CORRUPT", "the stored session was unreadable", LAUNCH_HINT);
1836
+ }
1837
+ if (session.state === "missing") {
1838
+ return err(
1839
+ "delete",
1840
+ "AUTH_FAILED",
1841
+ "no LinkedIn session \u2014 deleting goes over the private API",
1842
+ `Run \`lnrelay login\`. ${LAUNCH_HINT}`
1843
+ );
1844
+ }
1845
+ const refused = reserve("delete", now);
1846
+ if (refused !== null) return refused;
1847
+ const post = await lookup(urn, quiet);
1848
+ const plan = {
1849
+ action: "delete a post",
1850
+ payload: { urn },
1851
+ summary: [`post ${urn}`, ...previewLines(post)],
1852
+ reversibility: "NONE. A deleted post is gone, with its comments and reactions.",
1853
+ transport: "voyager"
1854
+ };
1855
+ const gated = await gateWrite("delete", plan, now, deps ?? terminalDeps());
1856
+ if ("ok" in gated) return gated;
1857
+ const result = await deletePost(gated.confirmed, createLiveClient(session.session));
1858
+ return result.ok ? ok("delete", { deleted: urn, verified: post !== void 0 }) : err("delete", result.code, result.message, result.hint);
1859
+ }
1860
+
1657
1861
  // src/commands/live.ts
1658
1862
  function withSession(command, quiet = false) {
1659
1863
  const loaded = loadSession();
@@ -1806,7 +2010,6 @@ function collection(result, opts = {}) {
1806
2010
  }
1807
2011
 
1808
2012
  // src/commands/local.ts
1809
- init_store();
1810
2013
  import { existsSync as existsSync2 } from "fs";
1811
2014
  import { version as nodeVersion } from "process";
1812
2015
  var LEDGER_FILE = "budget.json";
@@ -1938,6 +2141,290 @@ function runDoctor(now, offline) {
1938
2141
  });
1939
2142
  }
1940
2143
 
2144
+ // src/commands/oauth.ts
2145
+ import { spawn } from "child_process";
2146
+ import { createServer } from "http";
2147
+ import { createInterface as createInterface2 } from "readline/promises";
2148
+
2149
+ // src/engine/oauth.ts
2150
+ var AUTHORIZE = "https://www.linkedin.com/oauth/v2/authorization";
2151
+ var TOKEN = "https://www.linkedin.com/oauth/v2/accessToken";
2152
+ var USERINFO = "https://api.linkedin.com/v2/userinfo";
2153
+ var CALLBACK_PORT = 53682;
2154
+ var REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
2155
+ var SCOPES = ["openid", "profile", "w_member_social"];
2156
+ function authorizationUrl(clientId, state) {
2157
+ const params = new URLSearchParams({
2158
+ response_type: "code",
2159
+ client_id: clientId,
2160
+ redirect_uri: REDIRECT_URI,
2161
+ state,
2162
+ scope: SCOPES.join(" ")
2163
+ });
2164
+ return `${AUTHORIZE}?${params.toString()}`;
2165
+ }
2166
+ async function exchange(code, config, deps) {
2167
+ const body = new URLSearchParams({
2168
+ grant_type: "authorization_code",
2169
+ code,
2170
+ redirect_uri: REDIRECT_URI,
2171
+ client_id: config.clientId,
2172
+ client_secret: config.clientSecret
2173
+ });
2174
+ let res;
2175
+ try {
2176
+ res = await deps.fetch(TOKEN, {
2177
+ method: "POST",
2178
+ headers: { "content-type": "application/x-www-form-urlencoded" },
2179
+ body: body.toString()
2180
+ });
2181
+ } catch (e) {
2182
+ return { ok: false, message: `could not reach LinkedIn: ${e.message}` };
2183
+ }
2184
+ const text2 = await res.text();
2185
+ if (res.status !== 200) {
2186
+ return {
2187
+ ok: false,
2188
+ message: `LinkedIn rejected the code exchange (${res.status})`,
2189
+ // The most common causes, in the order they actually happen.
2190
+ 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)}`
2191
+ };
2192
+ }
2193
+ let parsed;
2194
+ try {
2195
+ parsed = JSON.parse(text2);
2196
+ } catch {
2197
+ return { ok: false, message: "token response was not JSON" };
2198
+ }
2199
+ const accessToken = parsed.access_token;
2200
+ const expiresIn = parsed.expires_in;
2201
+ if (typeof accessToken !== "string" || accessToken === "") {
2202
+ return { ok: false, message: "token response carried no access_token" };
2203
+ }
2204
+ const lifetimeMs = typeof expiresIn === "number" ? expiresIn * 1e3 : 60 * 864e5;
2205
+ return { ok: true, accessToken, expiresAt: deps.now() + lifetimeMs };
2206
+ }
2207
+ async function fetchMemberUrn(accessToken, deps) {
2208
+ let res;
2209
+ try {
2210
+ res = await deps.fetch(USERINFO, { headers: { authorization: `Bearer ${accessToken}` } });
2211
+ } catch (e) {
2212
+ return { ok: false, message: `could not reach userinfo: ${e.message}` };
2213
+ }
2214
+ if (res.status !== 200) {
2215
+ return {
2216
+ ok: false,
2217
+ message: `userinfo returned ${res.status} \u2014 the 'openid'/'profile' scopes may not be granted`
2218
+ };
2219
+ }
2220
+ const parsed = await res.json();
2221
+ if (typeof parsed.sub !== "string" || parsed.sub === "") {
2222
+ return { ok: false, message: "userinfo carried no subject claim" };
2223
+ }
2224
+ return { ok: true, memberUrn: `urn:li:person:${parsed.sub}` };
2225
+ }
2226
+ function parseCallback(rawUrl, expectedState) {
2227
+ let url;
2228
+ try {
2229
+ url = new URL(rawUrl, `http://localhost:${CALLBACK_PORT}`);
2230
+ } catch {
2231
+ return { ok: false, message: "callback URL was unparseable" };
2232
+ }
2233
+ const error = url.searchParams.get("error");
2234
+ if (error !== null) {
2235
+ const description = url.searchParams.get("error_description") ?? "";
2236
+ return { ok: false, message: `LinkedIn denied the request: ${error} ${description}`.trim() };
2237
+ }
2238
+ const state = url.searchParams.get("state");
2239
+ if (state !== expectedState) {
2240
+ return { ok: false, message: "state mismatch \u2014 this callback did not come from this login" };
2241
+ }
2242
+ const code = url.searchParams.get("code");
2243
+ if (code === null || code === "") return { ok: false, message: "callback carried no code" };
2244
+ return { ok: true, code };
2245
+ }
2246
+
2247
+ // src/commands/token.ts
2248
+ import { existsSync as existsSync3, rmSync } from "fs";
2249
+ var TOKEN_FILE = "oauth.json";
2250
+ var OAUTH_SETUP = [
2251
+ "Writes go over LinkedIn's OWN self-serve scope rather than the private API, which is the one",
2252
+ "legitimacy wedge an individual actually has \u2014 but the app has to be registered by you; it",
2253
+ "cannot be created on your behalf.",
2254
+ "",
2255
+ " 1. https://www.linkedin.com/developers/apps/new \u2014 create an app (any LinkedIn Page works).",
2256
+ ' 2. Products tab \u2192 add "Sign In with LinkedIn using OpenID Connect" AND "Share on LinkedIn".',
2257
+ " Both are self-serve: no partner review, no verification, no screencast.",
2258
+ ` 3. Auth tab \u2192 add redirect URL ${REDIRECT_URI}`,
2259
+ " 4. Run: lnrelay oauth login --client-id <id>",
2260
+ " (the secret is prompted for; or set LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET)"
2261
+ ].join("\n");
2262
+ function tokenPath() {
2263
+ return cachePath(TOKEN_FILE);
2264
+ }
2265
+ function loadToken() {
2266
+ const result = loadJson(tokenPath());
2267
+ return result.state === "ok" ? result.value : null;
2268
+ }
2269
+ function saveToken(token) {
2270
+ saveJson(tokenPath(), token);
2271
+ }
2272
+ function deleteToken() {
2273
+ const path = tokenPath();
2274
+ if (!existsSync3(path)) return false;
2275
+ rmSync(path, { force: true });
2276
+ return true;
2277
+ }
2278
+
2279
+ // src/commands/oauth.ts
2280
+ var CALLBACK_TIMEOUT_MS = 3e5;
2281
+ var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>lnrelay</title>
2282
+ <body style="font:16px system-ui;padding:3rem;max-width:32rem">
2283
+ <h1>Authorised.</h1><p>You can close this tab and go back to the terminal.</p>`;
2284
+ function listenForCallback(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
2285
+ return new Promise((ready) => {
2286
+ let settle = () => {
2287
+ };
2288
+ const code = new Promise((r) => {
2289
+ settle = r;
2290
+ });
2291
+ const server = createServer((req, res) => {
2292
+ const url = req.url ?? "/";
2293
+ if (!url.startsWith("/callback")) {
2294
+ res.writeHead(404, { connection: "close" });
2295
+ res.end();
2296
+ return;
2297
+ }
2298
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", connection: "close" });
2299
+ res.end(DONE_PAGE);
2300
+ settle(parseCallback(url, state));
2301
+ });
2302
+ const timer = setTimeout(() => {
2303
+ settle({
2304
+ ok: false,
2305
+ message: `timed out after ${Math.round(timeoutMs / 1e3)}s waiting for the LinkedIn callback`
2306
+ });
2307
+ }, timeoutMs);
2308
+ timer.unref?.();
2309
+ const close = () => {
2310
+ clearTimeout(timer);
2311
+ server.closeAllConnections?.();
2312
+ server.close();
2313
+ };
2314
+ server.once("error", (e) => {
2315
+ clearTimeout(timer);
2316
+ 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}`;
2317
+ ready({ ok: false, message: why });
2318
+ });
2319
+ server.listen(CALLBACK_PORT, "127.0.0.1", () => {
2320
+ ready({ ok: true, code, close });
2321
+ });
2322
+ });
2323
+ }
2324
+ function openBrowser(url) {
2325
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
2326
+ try {
2327
+ spawn(cmd, [url], { detached: true, stdio: "ignore" }).unref();
2328
+ } catch {
2329
+ }
2330
+ }
2331
+ function loginDeps() {
2332
+ return {
2333
+ state: () => crypto.randomUUID(),
2334
+ listen: (state) => listenForCallback(state),
2335
+ open: openBrowser,
2336
+ write: (s) => process.stderr.write(s),
2337
+ isTty: process.stdin.isTTY === true && process.stderr.isTTY === true,
2338
+ prompt: async (question) => {
2339
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
2340
+ const answer = await rl.question(question);
2341
+ rl.close();
2342
+ return answer;
2343
+ },
2344
+ now: Date.now,
2345
+ fetch: globalThis.fetch
2346
+ };
2347
+ }
2348
+ async function credentials(opts, deps) {
2349
+ const clientId = opts.clientId ?? process.env.LINKEDIN_CLIENT_ID;
2350
+ if (clientId === void 0 || clientId === "") {
2351
+ return err("oauth", "INVALID_INPUT", "a client id is required", OAUTH_SETUP);
2352
+ }
2353
+ let clientSecret = opts.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET;
2354
+ if ((clientSecret === void 0 || clientSecret === "") && deps.isTty) {
2355
+ clientSecret = (await deps.prompt("client secret (not echoed to argv or logs): ")).trim();
2356
+ }
2357
+ if (clientSecret === void 0 || clientSecret === "") {
2358
+ return err(
2359
+ "oauth",
2360
+ "INVALID_INPUT",
2361
+ "a client secret is required, and there is no terminal to ask on",
2362
+ `Set LINKEDIN_CLIENT_SECRET, or run this at an interactive terminal.
2363
+
2364
+ ${OAUTH_SETUP}`
2365
+ );
2366
+ }
2367
+ return { clientId, clientSecret };
2368
+ }
2369
+ async function runOauthLogin(opts, deps = loginDeps()) {
2370
+ const creds = await credentials(opts, deps);
2371
+ if ("ok" in creds) return creds;
2372
+ const state = deps.state();
2373
+ const listener = await deps.listen(state);
2374
+ if (!listener.ok) {
2375
+ return err("oauth", "AUTH_FAILED", listener.message);
2376
+ }
2377
+ try {
2378
+ const url = authorizationUrl(creds.clientId, state);
2379
+ deps.write(`Opening LinkedIn for consent. If nothing opens, visit:
2380
+
2381
+ ${url}
2382
+
2383
+ `);
2384
+ deps.open(url);
2385
+ const callback = await listener.code;
2386
+ if (!callback.ok) return err("oauth", "AUTH_FAILED", callback.message);
2387
+ const token = await exchange(callback.code, creds, { fetch: deps.fetch, now: deps.now });
2388
+ if (!token.ok) return err("oauth", "AUTH_FAILED", token.message, token.hint);
2389
+ const member = await fetchMemberUrn(token.accessToken, { fetch: deps.fetch });
2390
+ if (!member.ok) return err("oauth", "AUTH_FAILED", member.message, OAUTH_SETUP);
2391
+ saveToken({
2392
+ accessToken: token.accessToken,
2393
+ memberUrn: member.memberUrn,
2394
+ expiresAt: token.expiresAt
2395
+ });
2396
+ return ok("oauth", {
2397
+ memberUrn: member.memberUrn,
2398
+ scopes: SCOPES,
2399
+ expiresAt: new Date(token.expiresAt).toISOString(),
2400
+ storedAt: tokenPath(),
2401
+ // Refresh tokens are partner-gated, so renewal is re-running this.
2402
+ renewal: "run `lnrelay oauth login` again when it expires"
2403
+ });
2404
+ } finally {
2405
+ listener.close();
2406
+ }
2407
+ }
2408
+ function runOauthLogout() {
2409
+ const removed = deleteToken();
2410
+ return ok("oauth", {
2411
+ removed,
2412
+ note: removed ? `deleted ${tokenPath()} \u2014 the token stays valid on LinkedIn's side until it expires` : "no token was stored"
2413
+ });
2414
+ }
2415
+ function runOauthStatus() {
2416
+ const token = loadToken();
2417
+ if (token === null) return err("oauth", "AUTH_FAILED", "no OAuth token stored", OAUTH_SETUP);
2418
+ return ok("oauth", {
2419
+ memberUrn: token.memberUrn,
2420
+ expiresAt: new Date(token.expiresAt).toISOString(),
2421
+ expired: token.expiresAt <= Date.now(),
2422
+ scopes: SCOPES,
2423
+ storedAt: tokenPath(),
2424
+ writeCap: CAPS.write.perDay
2425
+ });
2426
+ }
2427
+
1941
2428
  // src/commands/registry.ts
1942
2429
  var COMMANDS = [
1943
2430
  // ─── local / meta — no network, available today ────────────────────────────
@@ -2110,8 +2597,8 @@ var COMMANDS = [
2110
2597
  {
2111
2598
  name: "oauth",
2112
2599
  cost: "free",
2113
- summary: "OAuth token status for writes. Never prints the token.",
2114
- usage: "lnrelay oauth",
2600
+ summary: "Obtain and inspect the write credential, over LinkedIn's own self-serve scope. Never prints the token.",
2601
+ 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
2602
  audience: ["cli"],
2116
2603
  risk: "local",
2117
2604
  implemented: true
@@ -2119,8 +2606,8 @@ var COMMANDS = [
2119
2606
  {
2120
2607
  name: "share",
2121
2608
  cost: "1 call \u2014 write",
2122
- summary: "Post to your own feed via LinkedIn's official OAuth scope.",
2123
- usage: 'lnrelay share "<text>" [--visibility public|connections]\n Stops and asks at an interactive terminal. No TTY = no write, and no network call.',
2609
+ summary: "Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the private API when no token exists \u2014 the prompt always names which.",
2610
+ usage: 'lnrelay share "<text>" [--visibility public|connections] [--via oauth|voyager]\n Stops and asks at an interactive terminal. No TTY = no write, and no network call.',
2124
2611
  audience: ["cli"],
2125
2612
  risk: "write",
2126
2613
  implemented: true
@@ -2134,6 +2621,15 @@ var COMMANDS = [
2134
2621
  risk: "write",
2135
2622
  implemented: true
2136
2623
  },
2624
+ {
2625
+ name: "delete",
2626
+ cost: "1 read + 1 write",
2627
+ summary: "Delete one of your own posts. Reads it first and shows you its text \u2014 this is the one action that cannot be undone.",
2628
+ usage: "lnrelay delete <urn:li:share:\u2026 | urn:li:activity:\u2026>",
2629
+ audience: ["cli"],
2630
+ risk: "write",
2631
+ implemented: true
2632
+ },
2137
2633
  {
2138
2634
  name: "react",
2139
2635
  cost: "1 call \u2014 write",
@@ -2161,7 +2657,6 @@ function helpText() {
2161
2657
  }
2162
2658
 
2163
2659
  // src/commands/sync.ts
2164
- init_db();
2165
2660
  var CONNECTIONS_MIN_INTERVAL_MS = 7 * 864e5;
2166
2661
  function searchText(item) {
2167
2662
  return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title].filter((v) => typeof v === "string").join(" ");
@@ -2174,6 +2669,76 @@ function diffSnapshot(before, seen, claimed) {
2174
2669
  if (!complete) return { removed: [], complete: false };
2175
2670
  return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };
2176
2671
  }
2672
+ async function syncMyPosts(engine, db, limit, now) {
2673
+ const me = await engine.whoami();
2674
+ if (!me.ok) return err("sync", me.code, me.message, me.hint);
2675
+ const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
2676
+ if (profileUrn === void 0) {
2677
+ return err("sync", "SCHEMA_DRIFT", "could not determine the owner profile urn");
2678
+ }
2679
+ const result = await engine.myPosts(profileUrn, limit);
2680
+ if (!result.ok) return err("sync", result.code, result.message, result.hint);
2681
+ const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
2682
+ const stored = upsert(db, "my-posts", rows, now);
2683
+ setCheckpoint(db, {
2684
+ source: "my-posts",
2685
+ lastSuccessfulAt: now,
2686
+ newestCreatedAt: null,
2687
+ headIds: rows.slice(0, 5).map((r) => r.urn),
2688
+ state: "ok"
2689
+ });
2690
+ return ok("sync", {
2691
+ source: "my-posts",
2692
+ ...stored,
2693
+ meta: result.value.parsed.meta,
2694
+ note: rows.length === 0 ? "LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch \u2014 meta.state says which." : void 0
2695
+ });
2696
+ }
2697
+ function tooSoon(db, now) {
2698
+ const cp = getCheckpoint(db, "connections");
2699
+ const age = cp === void 0 ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;
2700
+ if (age >= CONNECTIONS_MIN_INTERVAL_MS) return void 0;
2701
+ const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 864e5);
2702
+ return err(
2703
+ "sync",
2704
+ "BUDGET_EXHAUSTED",
2705
+ `connections were synced ${Math.floor(age / 864e5)} days ago`,
2706
+ `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`
2707
+ );
2708
+ }
2709
+ async function syncConnections(engine, db, limit, force, now) {
2710
+ const before = urnsFor(db, "connections");
2711
+ if (!force && before.size > 0) {
2712
+ const blocked = tooSoon(db, now);
2713
+ if (blocked !== void 0) return blocked;
2714
+ }
2715
+ const result = await engine.connections(limit);
2716
+ if (!result.ok) return err("sync", result.code, result.message, result.hint);
2717
+ const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
2718
+ const stored = upsert(db, "connections", rows, now);
2719
+ const claimed = result.value.parsed.meta.claimedCount;
2720
+ const seen = new Set(rows.map((r) => r.urn));
2721
+ const { removed, complete } = diffSnapshot(before, seen, claimed);
2722
+ if (removed.length > 0) removeUrns(db, "connections", removed);
2723
+ setCheckpoint(db, {
2724
+ source: "connections",
2725
+ lastSuccessfulAt: now,
2726
+ newestCreatedAt: null,
2727
+ headIds: [],
2728
+ // Honest: a snapshot, never a watermark.
2729
+ state: complete ? "ok" : "snapshot-partial"
2730
+ });
2731
+ return ok("sync", {
2732
+ source: "connections",
2733
+ added: stored.added,
2734
+ updated: stored.updated,
2735
+ removed: removed.length,
2736
+ claimed,
2737
+ complete,
2738
+ meta: result.value.parsed.meta,
2739
+ note: complete ? void 0 : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`
2740
+ });
2741
+ }
2177
2742
  async function runSync(source, limit, force, now = Date.now()) {
2178
2743
  if (source !== "my-posts" && source !== "connections") {
2179
2744
  return err(
@@ -2193,75 +2758,7 @@ async function runSync(source, limit, force, now = Date.now()) {
2193
2758
  const engine = createEngine(session.session);
2194
2759
  try {
2195
2760
  const db = openDb(now);
2196
- if (source === "my-posts") {
2197
- const me = await engine.whoami();
2198
- if (!me.ok) return err("sync", me.code, me.message, me.hint);
2199
- const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
2200
- if (profileUrn === void 0) {
2201
- return err("sync", "SCHEMA_DRIFT", "could not determine the owner profile urn");
2202
- }
2203
- const result2 = await engine.myPosts(profileUrn, limit);
2204
- if (!result2.ok) return err("sync", result2.code, result2.message, result2.hint);
2205
- const items2 = shapeAll(result2.value.parsed.items, result2.value.index);
2206
- const rows2 = rowsFrom(items2);
2207
- const stored2 = upsert(db, "my-posts", rows2, now);
2208
- setCheckpoint(db, {
2209
- source: "my-posts",
2210
- lastSuccessfulAt: now,
2211
- newestCreatedAt: null,
2212
- headIds: rows2.slice(0, 5).map((r) => r.urn),
2213
- state: "ok"
2214
- });
2215
- return ok("sync", {
2216
- source,
2217
- ...stored2,
2218
- meta: result2.value.parsed.meta,
2219
- note: rows2.length === 0 ? "LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch \u2014 meta.state says which." : void 0
2220
- });
2221
- }
2222
- const before = urnsFor(db, "connections");
2223
- const existing = before.size;
2224
- if (!force && existing > 0) {
2225
- const { getCheckpoint: getCheckpoint2 } = await Promise.resolve().then(() => (init_db(), db_exports));
2226
- const cp = getCheckpoint2(db, "connections");
2227
- const age = cp === void 0 ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;
2228
- if (age < CONNECTIONS_MIN_INTERVAL_MS) {
2229
- const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 864e5);
2230
- return err(
2231
- "sync",
2232
- "BUDGET_EXHAUSTED",
2233
- `connections were synced ${Math.floor(age / 864e5)} days ago`,
2234
- `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`
2235
- );
2236
- }
2237
- }
2238
- const result = await engine.connections(limit);
2239
- if (!result.ok) return err("sync", result.code, result.message, result.hint);
2240
- const items = shapeAll(result.value.parsed.items, result.value.index);
2241
- const rows = rowsFrom(items);
2242
- const stored = upsert(db, "connections", rows, now);
2243
- const claimed = result.value.parsed.meta.claimedCount;
2244
- const seen = new Set(rows.map((r) => r.urn));
2245
- const { removed, complete } = diffSnapshot(before, seen, claimed);
2246
- if (removed.length > 0) removeUrns(db, "connections", removed);
2247
- setCheckpoint(db, {
2248
- source: "connections",
2249
- lastSuccessfulAt: now,
2250
- newestCreatedAt: null,
2251
- headIds: [],
2252
- // Honest: a snapshot, never a watermark.
2253
- state: complete ? "ok" : "snapshot-partial"
2254
- });
2255
- return ok("sync", {
2256
- source,
2257
- added: stored.added,
2258
- updated: stored.updated,
2259
- removed: removed.length,
2260
- claimed,
2261
- complete,
2262
- meta: result.value.parsed.meta,
2263
- note: complete ? void 0 : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`
2264
- });
2761
+ return source === "my-posts" ? await syncMyPosts(engine, db, limit, now) : await syncConnections(engine, db, limit, force, now);
2265
2762
  } catch (e) {
2266
2763
  if (e instanceof CacheCorrupt) {
2267
2764
  return err(
@@ -2275,10 +2772,6 @@ async function runSync(source, limit, force, now = Date.now()) {
2275
2772
  }
2276
2773
  }
2277
2774
 
2278
- // src/commands/write.ts
2279
- init_store();
2280
- import { createInterface } from "readline/promises";
2281
-
2282
2775
  // src/engine/oauth-write.ts
2283
2776
  var API = "https://api.linkedin.com";
2284
2777
  function headers(token) {
@@ -2346,7 +2839,7 @@ async function send(url, body, token, deps) {
2346
2839
  function extractId(body) {
2347
2840
  return body.match(/"id"\s*:\s*"([^"]+)"/)?.[1] ?? null;
2348
2841
  }
2349
- function share(confirmed, token, deps) {
2842
+ function share2(confirmed, token, deps) {
2350
2843
  return send(
2351
2844
  `${API}/rest/posts`,
2352
2845
  {
@@ -2387,130 +2880,126 @@ function react(confirmed, token, deps) {
2387
2880
  );
2388
2881
  }
2389
2882
 
2390
- // src/commands/confirm.ts
2391
- import { createHash } from "crypto";
2392
- function confirmToken(action, payload) {
2393
- return createHash("sha256").update(`${action}:${JSON.stringify(payload)}`).digest("hex").slice(0, 4);
2394
- }
2395
- function renderPlan(plan, budgetLine2) {
2396
- const token = confirmToken(plan.action, plan.payload);
2397
- const lines = [
2398
- "",
2399
- ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
2400
- ` ${"\u2500".repeat(58)}`,
2401
- ...plan.summary.map((l) => ` ${l}`),
2402
- ` via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
2403
- ` undo ${plan.reversibility}`,
2404
- "",
2405
- " This automation breaches LinkedIn User Agreement \xA78.2 and can",
2406
- " permanently restrict this account.",
2407
- ` ${budgetLine2}`,
2408
- "",
2409
- ` Type ${token} to confirm, anything else to abort: `
2410
- ];
2411
- return lines.join("\n");
2412
- }
2413
- async function confirmWrite(plan, budgetLine2, deps) {
2414
- if (!deps.isTty) {
2883
+ // src/commands/transport.ts
2884
+ var NO_CREDENTIAL_HINT = [
2885
+ "Two ways to write, and you need one of them:",
2886
+ "",
2887
+ " Sanctioned lnrelay oauth login --client-id <id>",
2888
+ " Needs a developer app, which needs a LinkedIn Page.",
2889
+ "",
2890
+ " Unsanctioned lnrelay login",
2891
+ " Uses the same cookies as reads. No Page needed. Breaches \xA78.2",
2892
+ " and puts the account at risk \u2014 every write still asks first."
2893
+ ].join("\n");
2894
+ function chooseTransport(inputs, requested) {
2895
+ const { token, session, now } = inputs;
2896
+ const tokenLive = token !== null && token.expiresAt > now;
2897
+ if (requested === "oauth") {
2898
+ if (tokenLive) return { ok: true, transport: { kind: "oauth", token } };
2415
2899
  return {
2416
2900
  ok: false,
2417
- code: "CONFIRMATION_REQUIRED",
2418
- message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,
2419
- hint: "No terminal is attached, so nothing was sent and no network call was made. Run this command yourself in a shell. There is deliberately no --yes flag: an agent that could set one would not be confirming anything."
2901
+ message: token === null ? "no OAuth token stored" : "the OAuth token has expired",
2902
+ hint: "Run `lnrelay oauth login --client-id <id>`."
2420
2903
  };
2421
2904
  }
2422
- const token = confirmToken(plan.action, plan.payload);
2423
- const answer = (await deps.prompt(renderPlan(plan, budgetLine2))).trim();
2424
- if (answer !== token) {
2905
+ if (requested === "voyager") {
2906
+ if (session !== null) return { ok: true, transport: { kind: "voyager", session } };
2425
2907
  return {
2426
2908
  ok: false,
2427
- code: "CONFIRMATION_REQUIRED",
2428
- message: "aborted \u2014 the confirmation token did not match",
2429
- hint: "Nothing was sent. Re-run and type the token shown in the prompt."
2909
+ message: "no LinkedIn session \u2014 a Voyager write needs one",
2910
+ hint: "Run `lnrelay login` to mint one from your own browser."
2911
+ };
2912
+ }
2913
+ if (tokenLive) return { ok: true, transport: { kind: "oauth", token } };
2914
+ if (token !== null && session !== null) {
2915
+ return {
2916
+ ok: false,
2917
+ message: "the OAuth token has expired",
2918
+ hint: "Run `lnrelay oauth login --client-id <id>` to renew it. You do have a browser session, so `--via voyager` would also work \u2014 but that is the private API, and swapping you onto it because a token aged out is not a decision this tool will make for you."
2919
+ };
2920
+ }
2921
+ if (session !== null) {
2922
+ return {
2923
+ ok: true,
2924
+ transport: { kind: "voyager", session },
2925
+ note: "No OAuth token, so this write goes over the private API. See the prompt."
2430
2926
  };
2431
2927
  }
2432
2928
  return {
2433
- ok: true,
2434
- confirmed: { action: plan.action, payload: plan.payload, token }
2929
+ ok: false,
2930
+ message: "no way to write \u2014 no OAuth token and no session",
2931
+ hint: NO_CREDENTIAL_HINT
2435
2932
  };
2436
2933
  }
2437
2934
 
2438
2935
  // 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
- function ledger() {
2456
- const result = loadJson(cachePath("budget.json"));
2457
- return result.state === "ok" ? result.value : emptyLedger();
2458
- }
2459
- function budgetLine(now) {
2460
- const s = summarise(ledger(), "write", now);
2461
- return `${s.remaining} of ${s.cap} writes left today.`;
2462
- }
2463
- function terminalDeps() {
2464
- return {
2465
- isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,
2466
- prompt: async (question) => {
2467
- const rl = createInterface({ input: process.stdin, output: process.stderr });
2468
- const answer = await rl.question(question);
2469
- rl.close();
2470
- return answer;
2471
- },
2472
- write: (s) => process.stderr.write(s)
2473
- };
2936
+ function authorLine(transport) {
2937
+ return transport.kind === "oauth" ? `as ${transport.token.memberUrn}` : `as ${transport.session.ownerUrn ?? "you (browser session)"}`;
2474
2938
  }
2475
- function prepare(command, now) {
2476
- const token = loadToken();
2477
- if (token === null) {
2478
- return err(command, "AUTH_FAILED", "no OAuth token \u2014 writes need one", OAUTH_SETUP);
2479
- }
2480
- const attempt = spend(ledger(), "write", now);
2481
- if ("error" in attempt) {
2482
- return err(command, attempt.error.code, attempt.error.message, attempt.error.hint);
2483
- }
2484
- return { token, now };
2939
+ function prepare(command, now, via2) {
2940
+ const session = loadSession();
2941
+ const choice = chooseTransport(
2942
+ { token: loadToken(), session: session.state === "ok" ? session.session : null, now },
2943
+ via2
2944
+ );
2945
+ if (!choice.ok) {
2946
+ return err(command, "AUTH_FAILED", choice.message, `${choice.hint}
2947
+
2948
+ ${OAUTH_SETUP}`);
2949
+ }
2950
+ const refused = reserve(command, now);
2951
+ if (refused !== null) return refused;
2952
+ const ctx = { transport: choice.transport, now };
2953
+ if (choice.note !== void 0) ctx.note = choice.note;
2954
+ return ctx;
2955
+ }
2956
+ function oauthToken(ctx) {
2957
+ if (ctx.transport.kind !== "oauth") {
2958
+ throw new Error("oauthToken called on a non-oauth transport");
2959
+ }
2960
+ return ctx.transport.token;
2961
+ }
2962
+ function requireOauth(command, ctx) {
2963
+ if (ctx.transport.kind === "oauth") return null;
2964
+ return err(
2965
+ command,
2966
+ "NOT_IMPLEMENTED",
2967
+ `'${command}' is not implemented over the private API`,
2968
+ `Only 'share' is. The one available sample for ${command} disagrees with this tool's own verified read-side finding about which urn identifies the target, and a wrong urn doesn't error \u2014 it acts on the wrong post. Run \`bun run scripts/observe-write.ts\`, perform the action by hand once, and the capture settles it. See docs/research/W1-voyager-writes.md.`
2969
+ );
2485
2970
  }
2486
2971
  async function gate(command, plan, ctx, deps) {
2487
- const outcome = await confirmWrite(plan, budgetLine(ctx.now), deps);
2488
- if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);
2489
- const attempt = spend(ledger(), "write", ctx.now);
2490
- if ("permit" in attempt) saveJson(cachePath("budget.json"), attempt.ledger);
2491
- return { confirmed: outcome.confirmed };
2972
+ const gated = await gateWrite(command, plan, ctx.now, deps);
2973
+ if ("ok" in gated) return gated;
2974
+ return { confirmed: gated.confirmed };
2492
2975
  }
2493
- async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps()) {
2976
+ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps(), via2) {
2494
2977
  if (text2 === void 0 || text2.trim() === "") {
2495
2978
  return err("share", "INVALID_INPUT", "text is required", 'lnrelay share "<text>"');
2496
2979
  }
2497
2980
  const vis = visibility === "connections" ? "CONNECTIONS" : "PUBLIC";
2498
- const ctx = prepare("share", now);
2981
+ const ctx = prepare("share", now, via2);
2499
2982
  if ("ok" in ctx) return ctx;
2500
2983
  const plan = {
2501
2984
  action: "post to your feed",
2502
2985
  payload: { text: text2, visibility: vis },
2503
- summary: [`as ${ctx.token.memberUrn}`, `content "${text2}"`, `audience ${vis}`],
2504
- reversibility: "deletable from the LinkedIn UI; the post may be seen first",
2505
- transport: "oauth"
2986
+ summary: [authorLine(ctx.transport), `content "${text2}"`, `audience ${vis}`],
2987
+ reversibility: "deletable with `lnrelay delete <urn>`, but it is public under your name the moment it lands and anyone who saw it cannot un-see it",
2988
+ transport: ctx.transport.kind
2506
2989
  };
2507
2990
  const gated = await gate("share", plan, ctx, deps);
2508
2991
  if ("ok" in gated) return gated;
2509
- const result = await share(gated.confirmed, ctx.token, {
2992
+ const result = ctx.transport.kind === "oauth" ? await share2(gated.confirmed, ctx.transport.token, {
2510
2993
  fetch: globalThis.fetch,
2511
2994
  now: () => now
2995
+ }) : await share(gated.confirmed, createLiveClient(ctx.transport.session));
2996
+ if (!result.ok) return err("share", result.code, result.message, result.hint);
2997
+ return ok("share", {
2998
+ id: result.id ?? null,
2999
+ transport: ctx.transport.kind,
3000
+ url: "url" in result ? result.url : void 0,
3001
+ note: "note" in result ? result.note : ctx.note
2512
3002
  });
2513
- return result.ok ? ok("share", { id: result.id, url: result.url }) : err("share", result.code, result.message, result.hint);
2514
3003
  }
2515
3004
  async function runComment(postUrn, text2, now = Date.now(), deps = terminalDeps()) {
2516
3005
  if (postUrn === void 0 || text2 === void 0 || text2.trim() === "") {
@@ -2523,16 +3012,18 @@ async function runComment(postUrn, text2, now = Date.now(), deps = terminalDeps(
2523
3012
  }
2524
3013
  const ctx = prepare("comment", now);
2525
3014
  if ("ok" in ctx) return ctx;
3015
+ const unsupported = requireOauth("comment", ctx);
3016
+ if (unsupported !== null) return unsupported;
2526
3017
  const plan = {
2527
3018
  action: "comment on a post",
2528
3019
  payload: { postUrn, text: text2 },
2529
- summary: [`as ${ctx.token.memberUrn}`, `on ${postUrn}`, `content "${text2}"`],
3020
+ summary: [authorLine(ctx.transport), `on ${postUrn}`, `content "${text2}"`],
2530
3021
  reversibility: "deletable from the LinkedIn UI; the author is notified immediately",
2531
3022
  transport: "oauth"
2532
3023
  };
2533
3024
  const gated = await gate("comment", plan, ctx, deps);
2534
3025
  if ("ok" in gated) return gated;
2535
- const result = await comment(gated.confirmed, ctx.token, {
3026
+ const result = await comment(gated.confirmed, oauthToken(ctx), {
2536
3027
  fetch: globalThis.fetch,
2537
3028
  now: () => now
2538
3029
  });
@@ -2559,32 +3050,23 @@ async function runReact(postUrn, type, now = Date.now(), deps = terminalDeps())
2559
3050
  }
2560
3051
  const ctx = prepare("react", now);
2561
3052
  if ("ok" in ctx) return ctx;
3053
+ const unsupported = requireOauth("react", ctx);
3054
+ if (unsupported !== null) return unsupported;
2562
3055
  const plan = {
2563
3056
  action: "react to a post",
2564
3057
  payload: { postUrn, type: reaction },
2565
- summary: [`as ${ctx.token.memberUrn}`, `on ${postUrn}`, `reaction ${reaction}`],
3058
+ summary: [authorLine(ctx.transport), `on ${postUrn}`, `reaction ${reaction}`],
2566
3059
  reversibility: "removable from the LinkedIn UI; the author is notified immediately",
2567
3060
  transport: "oauth"
2568
3061
  };
2569
3062
  const gated = await gate("react", plan, ctx, deps);
2570
3063
  if ("ok" in gated) return gated;
2571
- const result = await react(gated.confirmed, ctx.token, {
3064
+ const result = await react(gated.confirmed, oauthToken(ctx), {
2572
3065
  fetch: globalThis.fetch,
2573
3066
  now: () => now
2574
3067
  });
2575
3068
  return result.ok ? ok("react", { id: result.id }) : err("react", result.code, result.message, result.hint);
2576
3069
  }
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
3070
 
2589
3071
  // src/entry.ts
2590
3072
  import { realpathSync } from "fs";
@@ -2629,6 +3111,30 @@ function output(args) {
2629
3111
  if (fields !== void 0) opts.fields = fields;
2630
3112
  return opts;
2631
3113
  }
3114
+ function via(args) {
3115
+ const value = str(args, "via");
3116
+ if (value === void 0) return void 0;
3117
+ return value === "oauth" || value === "voyager" ? value : "invalid";
3118
+ }
3119
+ async function oauth(args) {
3120
+ const sub = args.positionals[0] ?? "status";
3121
+ if (sub === "status") return runOauthStatus();
3122
+ if (sub === "logout") return runOauthLogout();
3123
+ if (sub === "login") {
3124
+ const opts = {};
3125
+ const id = str(args, "client-id");
3126
+ const secret = str(args, "client-secret");
3127
+ if (id !== void 0) opts.clientId = id;
3128
+ if (secret !== void 0) opts.clientSecret = secret;
3129
+ return runOauthLogin(opts);
3130
+ }
3131
+ return err(
3132
+ "oauth",
3133
+ "INVALID_INPUT",
3134
+ `unknown oauth subcommand '${sub}'`,
3135
+ "one of: login, status, logout"
3136
+ );
3137
+ }
2632
3138
  async function dispatch(argv, now) {
2633
3139
  const args = parseArgs(argv);
2634
3140
  const { command } = args;
@@ -2695,13 +3201,31 @@ async function dispatch(argv, now) {
2695
3201
  case "login":
2696
3202
  return runLogin();
2697
3203
  case "oauth":
2698
- return runOauthStatus();
2699
- case "share":
2700
- return runShare(args.positionals[0], str(args, "visibility") ?? "public", now);
3204
+ return oauth(args);
3205
+ case "share": {
3206
+ const surface = via(args);
3207
+ if (surface === "invalid") {
3208
+ return err(
3209
+ "share",
3210
+ "INVALID_INPUT",
3211
+ `unknown --via '${str(args, "via") ?? ""}'`,
3212
+ "one of: oauth, voyager. Omit it to prefer OAuth and fall back to Voyager."
3213
+ );
3214
+ }
3215
+ return runShare(
3216
+ args.positionals[0],
3217
+ str(args, "visibility") ?? "public",
3218
+ now,
3219
+ void 0,
3220
+ surface
3221
+ );
3222
+ }
2701
3223
  case "comment":
2702
3224
  return runComment(args.positionals[0], args.positionals[1], now);
2703
3225
  case "react":
2704
3226
  return runReact(args.positionals[0], str(args, "type") ?? "LIKE", now);
3227
+ case "delete":
3228
+ return runDelete(args.positionals[0], now, void 0, bool(args, "quiet"));
2705
3229
  case "whoami":
2706
3230
  return runWhoami(bool(args, "raw"));
2707
3231
  case "profile":