linkedin-relay-mcp 1.4.0 → 1.5.1

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
@@ -1799,6 +1799,10 @@ function terminalDeps() {
1799
1799
  write: (s) => process.stderr.write(s)
1800
1800
  };
1801
1801
  }
1802
+ function recordHarvestSpend(now) {
1803
+ const attempt = spend(ledger(), "page", now);
1804
+ if ("permit" in attempt) saveJson(cachePath("budget.json"), attempt.ledger);
1805
+ }
1802
1806
  function reserve(command, now) {
1803
1807
  const attempt = spend(ledger(), "write", now);
1804
1808
  return "error" in attempt ? err(command, attempt.error.code, attempt.error.message, attempt.error.hint) : null;
@@ -2668,8 +2672,8 @@ var COMMANDS = [
2668
2672
  {
2669
2673
  name: "comment",
2670
2674
  cost: "1 call \u2014 write",
2671
- summary: "Comment on a post. OAuth only \u2014 see the hint; not replayable over the private API.",
2672
- usage: 'lnrelay comment <activity-urn> "<text>"',
2675
+ summary: "Comment on a post. Harvests the binding tokens from the rendered page first \u2014 no browser needed, but it costs one heavy read.",
2676
+ usage: 'lnrelay comment <activity-urn> "<text>"\n Fetches the post page (~2.8 MB) to harvest a binding key and trackingId, proves the\n key belongs to that post, then asks. UNVERIFIED: never yet replayed successfully.',
2673
2677
  audience: ["cli"],
2674
2678
  risk: "write",
2675
2679
  implemented: true
@@ -2911,23 +2915,222 @@ function share2(confirmed, token, deps) {
2911
2915
  deps
2912
2916
  );
2913
2917
  }
2914
- function comment(confirmed, token, deps) {
2915
- const encoded = encodeURIComponent(confirmed.payload.postUrn);
2916
- return send(
2917
- `${API}/rest/socialActions/${encoded}/comments`,
2918
- {
2919
- actor: token.memberUrn,
2920
- object: confirmed.payload.postUrn,
2921
- message: { text: confirmed.payload.text }
2922
- },
2923
- token,
2924
- deps
2918
+
2919
+ // src/engine/sdui-harvest.ts
2920
+ function zigzag(n) {
2921
+ return n << 1n ^ n >> 63n;
2922
+ }
2923
+ function varint(n) {
2924
+ const out = [];
2925
+ let v = n;
2926
+ while (v > 0x7fn) {
2927
+ out.push(Number(v & 0x7fn | 0x80n));
2928
+ v >>= 7n;
2929
+ }
2930
+ out.push(Number(v));
2931
+ return out;
2932
+ }
2933
+ function activityIdSegment(activityId) {
2934
+ if (!/^\d+$/.test(activityId)) {
2935
+ throw new Error(`'${activityId}' is not a numeric activity id`);
2936
+ }
2937
+ const inner = [8, ...varint(zigzag(BigInt(activityId)))];
2938
+ const message = Uint8Array.from([10, inner.length, ...inner]);
2939
+ return btoa(String.fromCharCode(...message)).replace(/=+$/, "");
2940
+ }
2941
+ function keyMatchesPost(bindingKey, activityId) {
2942
+ try {
2943
+ return bindingKey.startsWith(`commentBoxText-${activityIdSegment(activityId)}-`);
2944
+ } catch {
2945
+ return false;
2946
+ }
2947
+ }
2948
+ var NOT_THE_POST = /checkpoint\/challenge|\/uas\/login|authwall|"status"\s*:\s*999/i;
2949
+ var TRACKING_PROXIMITY = 400;
2950
+ function updateTrackingId(html, activityId) {
2951
+ const idAt = [...html.matchAll(new RegExp(activityId, "g"))].map((m) => m.index ?? 0);
2952
+ if (idAt.length === 0) return null;
2953
+ const pattern = /trackingId(?:&quot;|\\?")+\s*:\s*(?:&quot;|\\?")+([A-Za-z0-9+/=]{16,32})/g;
2954
+ let best = null;
2955
+ for (const m of html.matchAll(pattern)) {
2956
+ const at = m.index ?? 0;
2957
+ const distance = Math.min(...idAt.map((p) => Math.abs(p - at)));
2958
+ if (best === null || distance < best.distance) best = { value: m[1], distance };
2959
+ }
2960
+ return best !== null && best.distance <= TRACKING_PROXIMITY ? best.value : null;
2961
+ }
2962
+ function extractCommentTokens(html, activityId) {
2963
+ if (NOT_THE_POST.test(html)) {
2964
+ return {
2965
+ ok: false,
2966
+ message: "the page returned was a challenge or sign-in wall, not the post",
2967
+ hint: "Re-mint the session with `lnrelay login`, then check `lnrelay risk`."
2968
+ };
2969
+ }
2970
+ let expected;
2971
+ try {
2972
+ expected = activityIdSegment(activityId);
2973
+ } catch (e) {
2974
+ return { ok: false, message: e.message };
2975
+ }
2976
+ const keyPattern = new RegExp(
2977
+ `commentBoxText-${expected.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-[A-Za-z0-9+/_=-]*FeedType_[A-Z_]+`
2925
2978
  );
2979
+ const key = keyPattern.exec(html)?.[0];
2980
+ if (key === void 0) {
2981
+ return {
2982
+ ok: false,
2983
+ message: `no comment-box binding key for post ${activityId} was found in the page`,
2984
+ hint: "Either the post does not accept comments, or LinkedIn changed the rendered shape. Re-capture with `bun run scripts/observe-write.ts` before changing this parser."
2985
+ };
2986
+ }
2987
+ const trackingId = updateTrackingId(html, activityId);
2988
+ if (trackingId === null) {
2989
+ return {
2990
+ ok: false,
2991
+ message: `no trackingId adjacent to post ${activityId} was found in the page`,
2992
+ hint: "The page carries several \u2014 one for the page itself, one per rendered update. Only the update's own will do, and guessing would build a malformed comment."
2993
+ };
2994
+ }
2995
+ return { ok: true, bindingKey: key, trackingId };
2926
2996
  }
2927
2997
 
2928
- // src/engine/sdui-write.ts
2998
+ // src/engine/sdui-comment.ts
2929
2999
  var SDUI_ACTION = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
3000
+ var COMMENT_URL = `${SDUI_ACTION}?sduiid=com.linkedin.sdui.comments.createComment`;
2930
3001
  var SCREEN_ID = "com.linkedin.sdui.flagshipnav.feed.UpdateDetail";
3002
+ var STATE_PREFIXES = [
3003
+ "commentBoxText",
3004
+ "richCommentBoxText",
3005
+ "commentBoxLinkPreviewIngestedContentId",
3006
+ "commentBoxExternalImageUrl",
3007
+ "commentBoxExternalImageId"
3008
+ ];
3009
+ var FEED_TYPES = { FEED_DETAIL: 3 };
3010
+ function keyBody(bindingKey) {
3011
+ return bindingKey.replace(/^commentBoxText-/, "");
3012
+ }
3013
+ function feedTypeFor(bindingKey) {
3014
+ const suffix = /FeedType_([A-Z_]+)$/.exec(bindingKey)?.[1];
3015
+ return suffix === void 0 ? null : FEED_TYPES[suffix] ?? null;
3016
+ }
3017
+ function stateKey(prefix, body) {
3018
+ return `${prefix}-${body}`;
3019
+ }
3020
+ function states(text2, body) {
3021
+ return STATE_PREFIXES.map((prefix) => {
3022
+ const key = stateKey(prefix, body);
3023
+ const base = {
3024
+ key,
3025
+ namespace: "MemoryNamespace",
3026
+ protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: key } }
3027
+ };
3028
+ if (prefix === "commentBoxText") {
3029
+ return { ...base, value: text2, originalProtoCase: "stringValue" };
3030
+ }
3031
+ if (prefix === "richCommentBoxText") {
3032
+ return {
3033
+ ...base,
3034
+ value: { text: text2, attribute: [], $type: "TextModel", source: "local" },
3035
+ originalProtoCase: "textModelForWrite"
3036
+ };
3037
+ }
3038
+ return { ...base, value: "", originalProtoCase: "stringValue" };
3039
+ });
3040
+ }
3041
+ function commentBody(activityId, text2, tokens, feedType) {
3042
+ const body = keyBody(tokens.bindingKey);
3043
+ const activityUrn = { activityUrn: { activityId } };
3044
+ const binding = (prefix) => ({
3045
+ key: stateKey(prefix, body),
3046
+ namespace: "MemoryNamespace"
3047
+ });
3048
+ const payload = {
3049
+ // The live client's handle for its optimistically-rendered comment. Server
3050
+ // relevance unknown, but it is cheap to send and being faithful to a
3051
+ // captured shape beats trimming fields whose purpose we are guessing at.
3052
+ optimisticKey: `auto-component-${crypto.randomUUID()}`,
3053
+ collection: {
3054
+ updateKey: {
3055
+ feedType,
3056
+ items: [
3057
+ { feedUpdateUrn: { updateUrnActivityUrn: activityUrn }, trackingId: tokens.trackingId }
3058
+ ],
3059
+ aggregationType: 0,
3060
+ isVideoCarousel: false
3061
+ },
3062
+ threadUrn: { threadUrnActivityThreadUrn: activityUrn }
3063
+ },
3064
+ commentFieldBinding: binding("commentBoxText"),
3065
+ richCommentFieldBinding: binding("richCommentBoxText"),
3066
+ linkPreviewIngestedContentId: binding("commentBoxLinkPreviewIngestedContentId"),
3067
+ externalImageUrl: binding("commentBoxExternalImageUrl"),
3068
+ externalImageId: binding("commentBoxExternalImageId")
3069
+ };
3070
+ const requestedStateKeys = STATE_PREFIXES.map((p) => ({
3071
+ key: { value: { $case: "id", id: stateKey(p, body) } }
3072
+ }));
3073
+ const args = {
3074
+ $type: "proto.sdui.actions.requests.RequestedArguments",
3075
+ requestedStateKeys,
3076
+ payload,
3077
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
3078
+ };
3079
+ return {
3080
+ requestId: "com.linkedin.sdui.comments.createComment",
3081
+ serverRequest: {
3082
+ requestId: "com.linkedin.sdui.comments.createComment",
3083
+ requestedArguments: args,
3084
+ isApfcEnabled: false,
3085
+ isStreaming: false,
3086
+ rumPageKey: ""
3087
+ },
3088
+ states: states(text2, body),
3089
+ requestedArguments: {
3090
+ ...args,
3091
+ states: states(text2, body),
3092
+ screenId: SCREEN_ID,
3093
+ knownTemplateIds: []
3094
+ }
3095
+ };
3096
+ }
3097
+ async function comment(confirmed, client) {
3098
+ const { activityId, text: text2, tokens } = confirmed.payload;
3099
+ if (!keyMatchesPost(tokens.bindingKey, activityId)) {
3100
+ return {
3101
+ ok: false,
3102
+ code: "INVALID_INPUT",
3103
+ message: "the harvested binding key does not belong to this post",
3104
+ hint: "Refusing to send: this is how a comment lands on the wrong post. Re-harvest."
3105
+ };
3106
+ }
3107
+ const feedType = feedTypeFor(tokens.bindingKey);
3108
+ if (feedType === null) {
3109
+ return {
3110
+ ok: false,
3111
+ code: "NOT_IMPLEMENTED",
3112
+ message: `unknown feed type in binding key '${tokens.bindingKey.slice(-24)}'`,
3113
+ hint: "Only FeedType_FEED_DETAIL has been observed, carrying feedType 3. Inventing a number for another context would be a malformed write against a real post. Capture the missing one with `bun run scripts/observe-write.ts`."
3114
+ };
3115
+ }
3116
+ const result = await client.request({
3117
+ url: COMMENT_URL,
3118
+ method: "POST",
3119
+ body: commentBody(activityId, text2, tokens, feedType),
3120
+ spendClass: "write",
3121
+ operation: "comment.create"
3122
+ });
3123
+ if (!result.ok) {
3124
+ const out = { ok: false, code: result.code, message: result.message };
3125
+ if (result.hint !== void 0) out.hint = result.hint;
3126
+ return out;
3127
+ }
3128
+ return { ok: true, id: activityId };
3129
+ }
3130
+
3131
+ // src/engine/sdui-write.ts
3132
+ var SDUI_ACTION2 = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
3133
+ var SCREEN_ID2 = "com.linkedin.sdui.flagshipnav.feed.UpdateDetail";
2931
3134
  var REACTIONS = [
2932
3135
  "LIKE",
2933
3136
  "PRAISE",
@@ -2948,7 +3151,7 @@ function reactionLabel(reaction) {
2948
3151
  return LABELS[reaction];
2949
3152
  }
2950
3153
  function reactionUrl(op) {
2951
- return `${SDUI_ACTION}?sduiid=com.linkedin.sdui.reactions.${op}`;
3154
+ return `${SDUI_ACTION2}?sduiid=com.linkedin.sdui.reactions.${op}`;
2952
3155
  }
2953
3156
  function targetFor(urn) {
2954
3157
  const comment2 = /^urn:li:comment:\((urn:li:activity:\d+),(\d+)\)$/.exec(urn);
@@ -3004,7 +3207,7 @@ function sduiBody(op, target, reaction) {
3004
3207
  requestedArguments: {
3005
3208
  ...args,
3006
3209
  states: [],
3007
- screenId: SCREEN_ID,
3210
+ screenId: SCREEN_ID2,
3008
3211
  knownTemplateIds: []
3009
3212
  }
3010
3213
  };
@@ -3104,21 +3307,6 @@ ${OAUTH_SETUP}`);
3104
3307
  if (choice.note !== void 0) ctx.note = choice.note;
3105
3308
  return ctx;
3106
3309
  }
3107
- function oauthToken(ctx) {
3108
- if (ctx.transport.kind !== "oauth") {
3109
- throw new Error("oauthToken called on a non-oauth transport");
3110
- }
3111
- return ctx.transport.token;
3112
- }
3113
- function requireOauth(command, ctx) {
3114
- if (ctx.transport.kind === "oauth") return null;
3115
- return err(
3116
- command,
3117
- "NOT_IMPLEMENTED",
3118
- `'${command}' is not implemented over the private API`,
3119
- "Commenting was captured from the live client on 2026-08-13 and is NOT replayable as a single request: com.linkedin.sdui.comments.createComment carries a trackingId from the feed render and an opaque binding key that only exists once a page has been rendered. Reaching it means fetching the SDUI screen first to harvest both. `share`, `delete` and `react` work over the private API. See docs/research/W5-sdui-writes.md."
3120
- );
3121
- }
3122
3310
  async function gate(command, plan, ctx, deps) {
3123
3311
  const gated = await gateWrite(command, plan, ctx.now, deps, {
3124
3312
  commitSpend: ctx.transport.kind === "oauth"
@@ -3154,6 +3342,35 @@ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps
3154
3342
  note: "note" in result ? result.note : ctx.note
3155
3343
  });
3156
3344
  }
3345
+ function activityIdOf(urn) {
3346
+ return /^urn:li:(?:activity|ugcPost|share):(\d+)$/.exec(urn)?.[1] ?? null;
3347
+ }
3348
+ async function harvest(activityId, session, now) {
3349
+ const spent = reserve("comment", now);
3350
+ if (spent !== null) return spent;
3351
+ recordHarvestSpend(now);
3352
+ const headers2 = buildHeaders(session);
3353
+ let html;
3354
+ try {
3355
+ const res = await fetch(`https://www.linkedin.com/feed/update/urn:li:activity:${activityId}/`, {
3356
+ headers: {
3357
+ cookie: headers2.cookie ?? "",
3358
+ "user-agent": headers2["user-agent"] ?? "",
3359
+ accept: "text/html"
3360
+ },
3361
+ redirect: "manual"
3362
+ });
3363
+ if (res.status !== 200) {
3364
+ return err("comment", "FETCH_FAILED", `the post page returned ${res.status}`);
3365
+ }
3366
+ html = await res.text();
3367
+ } catch (e) {
3368
+ return err("comment", "FETCH_FAILED", `could not load the post page: ${e.message}`);
3369
+ }
3370
+ const found = extractCommentTokens(html, activityId);
3371
+ if (!found.ok) return err("comment", "SCHEMA_DRIFT", found.message, found.hint);
3372
+ return { ok: true, tokens: { bindingKey: found.bindingKey, trackingId: found.trackingId } };
3373
+ }
3157
3374
  async function runComment(postUrn2, text2, now = Date.now(), deps = terminalDeps()) {
3158
3375
  if (postUrn2 === void 0 || text2 === void 0 || text2.trim() === "") {
3159
3376
  return err(
@@ -3163,24 +3380,40 @@ async function runComment(postUrn2, text2, now = Date.now(), deps = terminalDeps
3163
3380
  'lnrelay comment <urn> "<text>"'
3164
3381
  );
3165
3382
  }
3166
- const ctx = prepare("comment", now);
3383
+ const activityId = activityIdOf(postUrn2);
3384
+ if (activityId === null) {
3385
+ return err("comment", "INVALID_INPUT", `'${postUrn2}' does not identify a post`);
3386
+ }
3387
+ if (!deps.isTty) {
3388
+ return err(
3389
+ "comment",
3390
+ "CONFIRMATION_REQUIRED",
3391
+ "commenting needs a human to confirm it at an interactive terminal",
3392
+ "No terminal is attached, so nothing was sent and no network call was made."
3393
+ );
3394
+ }
3395
+ const ctx = prepare("comment", now, "voyager");
3167
3396
  if ("ok" in ctx) return ctx;
3168
- const unsupported = requireOauth("comment", ctx);
3169
- if (unsupported !== null) return unsupported;
3397
+ if (ctx.transport.kind !== "voyager") {
3398
+ return err("comment", "NOT_IMPLEMENTED", "commenting is only implemented over the private API");
3399
+ }
3400
+ const harvested = await harvest(activityId, ctx.transport.session, now);
3401
+ if ("ok" in harvested && harvested.ok !== true) return harvested;
3402
+ if (!("tokens" in harvested)) return harvested;
3170
3403
  const plan = {
3171
3404
  action: "comment on a post",
3172
- payload: { postUrn: postUrn2, text: text2 },
3405
+ payload: { activityId, text: text2, tokens: harvested.tokens },
3173
3406
  summary: [authorLine(ctx.transport), `on ${postUrn2}`, `content "${text2}"`],
3174
- reversibility: "deletable from the LinkedIn UI; the author is notified immediately",
3175
- transport: "oauth"
3407
+ reversibility: "deletable from the LinkedIn UI; the author is notified immediately and cannot un-see it",
3408
+ transport: "voyager"
3176
3409
  };
3177
3410
  const gated = await gate("comment", plan, ctx, deps);
3178
3411
  if ("ok" in gated) return gated;
3179
- const result = await comment(gated.confirmed, oauthToken(ctx), {
3180
- fetch: globalThis.fetch,
3181
- now: () => now
3182
- });
3183
- return result.ok ? ok("comment", { id: result.id }) : err("comment", result.code, result.message, result.hint);
3412
+ const result = await comment(
3413
+ gated.confirmed,
3414
+ createLiveClient(ctx.transport.session)
3415
+ );
3416
+ return result.ok ? ok("comment", { id: result.id, on: postUrn2 }) : err("comment", result.code, result.message, result.hint);
3184
3417
  }
3185
3418
  var REACTIONS2 = REACTIONS;
3186
3419
  async function runReact(postUrn2, type, now = Date.now(), deps = terminalDeps(), remove = false) {