tentek-poster 0.0.0-stage → 0.11.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
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # Tentek Poster
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP-сервер для публикации статей и постов на **vc.ru, DTF, Дзен, Пикабу, TenChat, Сетку и Хабр**
4
+ через их внутренние API — запросы идут из вашей сессии браузера через расширение.
5
+
6
+ | Площадка | `site` | Черновики | Формат / ограничения |
7
+ |---|---|---|---|
8
+ | vc.ru | `vc` | на сайте | блоки Osnova; работает и без расширения (токен) |
9
+ | DTF | `dtf` | на сайте | то же |
10
+ | Дзен | `dzen` | на сайте | Draft.js; id канала в `~/.config/tentek-poster/config.json`; публикация может попросить капчу |
11
+ | Пикабу | `pikabu` | на сайте, до 10 | HTML-блоки; для публикации 2–20 тегов (`tags`) |
12
+ | TenChat | `tenchat` | на сайте, 30 дней | Markdown без подзаголовков и курсива; до 7000 символов |
13
+ | Сетка | `setka` | **локально** (на сайте их нет) | заголовок ≤60, текст ≤4096; без подзаголовков и списков; `publish` сразу публикует |
14
+ | Хабр | `habr` | на сайте | Markdown; даже черновику нужны `hubs` (1–5), `tags` (1–10), `flow` (аудитория) и лид ≥100 символов; из Песочницы `publish` = отправка на модерацию | Дизайн и найденный формат API — в [docs/design.md](docs/design.md).
15
+
16
+ ## Установка в Claude Desktop (одним файлом)
17
+
18
+ Скачайте [tentek-poster.mcpb](https://github.com/kaicex/tentek-poster-releases/releases/latest/download/tentek-poster.mcpb) и откройте его двойным кликом: Claude Desktop
19
+ сам установит сервер, Node и правка конфига не нужны. Затем поставьте расширение
20
+ Tentek Poster в браузер (см. ниже).
21
+
22
+ Собрать файл: `bash scripts/build-mcpb.sh` → `build/tentek-poster-<версия>.mcpb`
23
+ (версия берётся из `extension/manifest.json`, манифест пакета — `mcpb/manifest.json`).
24
+ Выпуск: `gh release create v<версия> <файл, переименованный в tentek-poster.mcpb> --repo kaicex/tentek-poster-releases`.
25
+ Имя файла в выпуске всегда `tentek-poster.mcpb`, тогда ссылка `releases/latest/download/…` не меняется.
26
+
27
+ ## Установка из исходников (Claude Code, разработка)
28
+
29
+ ```bash
30
+ npm install
31
+ npm run build
32
+ ```
33
+
34
+ ## Расширение браузера (рекомендуется)
35
+
36
+ Расширение выполняет запросы через ваш обычный вход на vc.ru и DTF: токены копировать не нужно,
37
+ и из браузера вас не выкидывает (новый токен записывается обратно на сайт).
38
+
39
+ 1. Откройте `chrome://extensions` (в Яндекс Браузере — `browser://extensions`).
40
+ 2. Включите «Режим разработчика».
41
+ 3. «Загрузить распакованное расширение» → папка `extension/` этого проекта.
42
+ 4. Войдите на vc.ru и/или dtf.ru в этом браузере.
43
+
44
+ Расширение само подключается к серверу (`ws://127.0.0.1:47615`) и переподключается, если сервер перезапустили.
45
+ В окне расширения — список площадок:
46
+ - **переключатель** у каждой: выключенная площадка недоступна Claude (инструменты отвечают «отключена в расширении»);
47
+ - **цвет переключателя** — состояние входа: зелёный — вход есть, рыжий — есть замечание, красный — входа нет, серый — не проверялось / сайт не отвечает;
48
+ - последний известный аккаунт запоминается и показывается всегда;
49
+ - **⟳** при наведении на строку — проверить только эту площадку; «Проверить все» — все включённые.
50
+ - «черновиков: N» — сколько черновиков на площадке, ссылка ведёт в раздел черновиков; клик по логотипу открывает сайт;
51
+ - **«Последние действия»** — что Claude создал, обновил, опубликовал или удалил (последние 30), со ссылками.
52
+
53
+ Запросы идут **без вкладок** — прямо из фона расширения с вашими cookie (служебные значения берутся из cookie или HTML страницы). Если сайт так не пускает, расширение открывает фоновую вкладку в свёрнутой группе «Tentek Poster» и закрывает её после работы. vc.ru и DTF изредка открывают вкладку для обновления токена.
54
+ То же из Claude — инструмент `status` с `check_accounts: true`. Принимаются только подключения от расширений — сайты подключиться не могут.
55
+
56
+ Если браузер с расширением закрыт, vc.ru и DTF работают через сохранённый токен (см. ниже), если он есть.
57
+
58
+ **Несколько окон Claude Code.** Порт один, поэтому первый запущенный сервер становится основным, а остальные
59
+ передают запросы через него (ключ — `~/.config/tentek-poster/relay.key`, права 600). Если основной закрылся,
60
+ его место за ~3 секунды занимает следующий.
61
+
62
+ ## Токен площадки (запасной вариант, один раз на сайт)
63
+
64
+ ```bash
65
+ npm run set-token -- vc
66
+ ```
67
+
68
+ Скрипт подскажет: открыть сайт в браузере под своим аккаунтом, в DevTools → Console выполнить
69
+ `localStorage.getItem("auth-refresh-token")` и вставить результат. Токен хранится в
70
+ `~/.config/tentek-poster/tokens.json` (права 600); сервер сам его обновляет.
71
+
72
+ > Сервер обновляет токен с ротацией, поэтому вход в браузере после этого может слететь — просто войдите заново.
73
+ > Перевход для сервера нужен только если им долго не пользовались, вы вышли со всех устройств или сменили пароль.
74
+
75
+ ## Подключение к Claude Code
76
+
77
+ ```bash
78
+ claude mcp add tentek-poster -- node "/Users/user/Documents/development/Longread MCP/dist/index.js"
79
+ ```
80
+
81
+ ## Инструменты
82
+
83
+ | Инструмент | Что делает |
84
+ |---|---|
85
+ | `create_draft(site, markdown, title?)` | Черновик из Markdown. Не публикует. Без `title` берётся первый `# Заголовок` |
86
+ | `update_draft(site, id, markdown, title?)` | Полностью заменяет текст черновика |
87
+ | `publish(site, id)` | Публикует черновик |
88
+ | `list_drafts(site, limit?)` | Список черновиков |
89
+ | `get_draft(site, id)` | Читает черновик обратно в Markdown (с заголовком и параметрами) — вызывать перед `update_draft` |
90
+ | `delete_draft(site, id)` | Безвозвратно удаляет черновик. Опубликованные записи не трогает (на vc/DTF и Дзене это проверяется) |
91
+ | `status(check_accounts?)` | Связь с расширением; с `check_accounts` — вход на каждой площадке |
92
+ | `set_token(site, refresh_token)` | То же, что `npm run set-token`, но через Claude (токен пройдёт через чат) |
93
+ | `set_account(telegram)` | Привязывает подписку PRO по Telegram-логину (пустая строка — выйти) |
94
+
95
+ Публикация (`publish`) на Дзене, Пикабу, TenChat и Сетке написана по коду сайтов и ещё не проверялась вживую.
96
+
97
+ ## Тарифы
98
+
99
+ **Бесплатно:** любые 2 площадки и 10 публикаций в месяц. Публикацией считается новый пост
100
+ на площадке (`create_draft`); правки, чтение, удаление и `publish` не считаются, удаление
101
+ лимит не возвращает. Одна статья на vc.ru и Хабр — 2 публикации. Счётчик обнуляется 1-го
102
+ числа по местному времени. Пока две площадки не выбраны, бесплатными становятся первые две,
103
+ куда напишет Claude; поменять можно в окне расширения (× у площадки в блоке тарифа).
104
+
105
+ **PRO** — все 8 площадок без лимита: 490 ₽ за месяц, 1 240 ₽ за 3 месяца, 3 900 ₽ за год.
106
+ Оплата в Telegram через Tribute (карты любой страны, Apple Pay) — кнопка «Оформить PRO» в окне
107
+ расширения. После оплаты войдите по Telegram-логину: в окне расширения («Уже оплатили?») или
108
+ сказав Claude «мой Telegram — @логин».
109
+
110
+ Подписка проверяется в Tribute Manager; если он не отвечает, действующая по сроку подписка
111
+ остаётся в силе. Состояние — `~/.config/tentek-poster/plan.json`. Пока `PLAN.API_KEY` в
112
+ `src/plan.ts` пустой, ограничений нет.
113
+
114
+ ## Картинки
115
+
116
+ Картинка — отдельным абзацем: `![подпись](путь или URL)` (локальный файл, `~/…`, http(s) или data-URI; PNG/JPEG/GIF/WebP до 15 МБ).
117
+
118
+ | Площадка | Как размещается |
119
+ |---|---|
120
+ | vc.ru, DTF | блок изображения в тексте (загрузка с сервера, без расширения) |
121
+ | Дзен | блок изображения; первая картинка — обложка |
122
+ | Пикабу | блок изображения с подписью |
123
+ | Хабр | перезаливается на habrastorage, в тексте остаётся `![]()` |
124
+ | TenChat | только галерея над текстом (первая — обложка) |
125
+ | Сетка | вложения к посту (до 10), загружаются при `publish` |
126
+
127
+ Картинка внутри строки текста (не отдельным абзацем) остаётся ссылкой.
128
+
129
+ ## Ограничения
130
+ - Таблицы превращаются в строки текста, код — в текстовый блок с `<code>`.
131
+ - API неофициальные: при изменениях на сайте может понадобиться правка модуля в `src/platforms/`.
132
+ - Живая проверка черновиков: `node scripts/live-test.mjs vc,dtf,dzen,pikabu,tenchat,setka` (создаёт тестовые черновики, ничего не публикует).
133
+
134
+ ## Разработка
135
+
136
+ ```bash
137
+ npm test # vitest, без сети
138
+ npm run dev # запуск из исходников
139
+ ```
package/dist/bridge.js ADDED
@@ -0,0 +1,457 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { WebSocket, WebSocketServer } from "ws";
5
+ import { CONFIG_DIR } from "./config.js";
6
+ import { OsnovaError } from "./osnova.js";
7
+ export const BRIDGE_PORT = Number(process.env.LONGREAD_MCP_PORT ?? 47615);
8
+ const REQUEST_TIMEOUT_MS = 90_000;
9
+ const RELAY_HEADER = "x-longread-relay";
10
+ const PROTOCOL_HEADER = "x-longread-protocol";
11
+ /**
12
+ * Bump when the bridge or the messages it serves change. A newer instance
13
+ * takes the primary role over from an older one, so a stale server left
14
+ * running in some Claude Code window can't keep serving old behaviour.
15
+ */
16
+ export const BRIDGE_PROTOCOL = 9;
17
+ const ROLE_CHECK_MS = 3000;
18
+ /**
19
+ * Only browser extensions may connect: browsers always send an Origin header
20
+ * and web pages cannot fake a chrome-extension:// origin.
21
+ */
22
+ export function isExtensionOrigin(origin) {
23
+ return typeof origin === "string" && /^chrome-extension:\/\/[a-p]{32}$/.test(origin);
24
+ }
25
+ const log = (...a) => console.error("[tentek-poster]", ...a);
26
+ /** Shared secret that lets local MCP instances relay through each other. */
27
+ async function loadRelayKey(path) {
28
+ try {
29
+ return (await readFile(path, "utf8")).trim();
30
+ }
31
+ catch {
32
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
33
+ const key = randomBytes(32).toString("hex");
34
+ try {
35
+ await writeFile(path, key, { mode: 0o600, flag: "wx" });
36
+ return key;
37
+ }
38
+ catch {
39
+ return (await readFile(path, "utf8")).trim(); // another instance created it first
40
+ }
41
+ }
42
+ }
43
+ const sameKey = (a, b) => typeof a === "string" && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
44
+ /** One connected extension instance (a browser or browser profile). */
45
+ class Peer {
46
+ ws;
47
+ version;
48
+ browser;
49
+ connectedAt = Date.now();
50
+ pending = new Map();
51
+ constructor(ws) {
52
+ this.ws = ws;
53
+ }
54
+ get open() {
55
+ return this.ws.readyState === 1;
56
+ }
57
+ get label() {
58
+ return `${this.browser ?? "браузер"} (v${this.version ?? "?"})`;
59
+ }
60
+ }
61
+ /**
62
+ * Connection to the Tentek Poster browser extension.
63
+ *
64
+ * Only one process can listen on the bridge port, but Claude Code may run
65
+ * several MCP server instances (one per window/session). The first instance
66
+ * becomes **primary**: it listens, the extension connects to it. Others become
67
+ * **relays**: they connect to the primary (authenticated with a key file only
68
+ * local processes can read) and send their requests through it. If the primary
69
+ * exits, a relay takes over the port.
70
+ *
71
+ * Several extension instances may be connected at once (two browsers or
72
+ * profiles). A request goes to the newest; on failure the next one is tried.
73
+ */
74
+ export class ExtensionBridge {
75
+ port;
76
+ host;
77
+ keyPath;
78
+ protocol;
79
+ name = "расширение";
80
+ mode = "none";
81
+ wss;
82
+ peers = new Set();
83
+ relays = new Set();
84
+ relaySocket;
85
+ relayPending = new Map();
86
+ remote = { connected: false, peers: [], disabled: [] };
87
+ /** Platform ids switched off in the extension (primary: from the extension; relay: from the primary). */
88
+ disabledLocal = new Set();
89
+ /** Platforms the user switched off in the extension popup. */
90
+ disabledSites() {
91
+ return this.mode === "relay" ? this.remote.disabled : [...this.disabledLocal];
92
+ }
93
+ isDisabled(site) {
94
+ return this.disabledSites().includes(site);
95
+ }
96
+ key;
97
+ timer;
98
+ stopped = false;
99
+ nextId = 1;
100
+ /** Set by the server: runs every platform's account check (for the popup). */
101
+ onCheckAccounts;
102
+ /** Set by the server: answers the popup's paid-tier requests. */
103
+ onPlanMessage;
104
+ /** Set by the server: a relay did something that may change the plan (primary only). */
105
+ onPlanChanged;
106
+ /** Sends the paid-tier state to every connected extension (the primary owns them). */
107
+ pushPlan(plan) {
108
+ if (this.mode === "relay")
109
+ return;
110
+ for (const p of this.openPeers())
111
+ p.ws.send(JSON.stringify({ type: "plan", plan }));
112
+ }
113
+ constructor(port = BRIDGE_PORT, host = "127.0.0.1", keyPath = join(CONFIG_DIR, "relay.key"), protocol = BRIDGE_PROTOCOL) {
114
+ this.port = port;
115
+ this.host = host;
116
+ this.keyPath = keyPath;
117
+ this.protocol = protocol;
118
+ }
119
+ /** After stepping down, don't grab the port back before the newer instance does. */
120
+ holdOffUntil = 0;
121
+ /** Extensions that are connected and introduced themselves (sent "hello"). */
122
+ openPeers() {
123
+ return [...this.peers].filter((p) => p.open && p.version !== undefined).sort((a, b) => b.connectedAt - a.connectedAt);
124
+ }
125
+ get connected() {
126
+ if (this.mode === "relay")
127
+ return this.relaySocket?.readyState === WebSocket.OPEN && this.remote.connected;
128
+ return this.openPeers().length > 0;
129
+ }
130
+ /** Human-readable list of connected extension instances. */
131
+ describePeers() {
132
+ return this.mode === "relay" ? this.remote.peers : this.openPeers().map((p) => p.label);
133
+ }
134
+ /**
135
+ * Become primary, or relay through an existing primary. Keeps re-checking the
136
+ * role in the background. Resolves true once a role (primary or relay) is taken.
137
+ */
138
+ async start() {
139
+ this.key = await loadRelayKey(this.keyPath);
140
+ await this.ensureRole();
141
+ this.timer = setInterval(() => void this.ensureRole(), ROLE_CHECK_MS);
142
+ this.timer.unref();
143
+ return this.mode !== "none";
144
+ }
145
+ async ensureRole() {
146
+ if (this.stopped || this.mode === "primary")
147
+ return;
148
+ if (this.mode === "relay" && this.relaySocket?.readyState === WebSocket.OPEN)
149
+ return;
150
+ if (Date.now() >= this.holdOffUntil && (await this.listen()))
151
+ return;
152
+ await this.connectRelay();
153
+ }
154
+ /** A newer instance connected: hand the port over to it and become a relay. */
155
+ async stepDown(newer) {
156
+ log(`primary: a newer instance (protocol ${newer} > ${this.protocol}) is running — handing over the port`);
157
+ this.holdOffUntil = Date.now() + 8000;
158
+ this.mode = "none";
159
+ for (const p of this.peers)
160
+ p.ws.close(1012, "primary changed"); // the extension reconnects to the new one
161
+ for (const r of this.relays)
162
+ r.close(1012, "primary changed");
163
+ const wss = this.wss;
164
+ this.wss = undefined;
165
+ await new Promise((r) => (wss ? wss.close(() => r()) : r()));
166
+ }
167
+ listen() {
168
+ return new Promise((resolve) => {
169
+ const wss = new WebSocketServer({
170
+ host: this.host,
171
+ port: this.port,
172
+ verifyClient: ({ origin, req }) => isExtensionOrigin(origin) || (!origin && sameKey(req.headers[RELAY_HEADER], this.key)),
173
+ });
174
+ wss.once("listening", () => {
175
+ this.wss = wss;
176
+ this.mode = "primary";
177
+ this.relaySocket?.close();
178
+ log(`primary: listening on ws://${this.host}:${this.port}`);
179
+ resolve(true);
180
+ });
181
+ wss.once("error", (e) => {
182
+ if (e.code !== "EADDRINUSE")
183
+ log(e.message);
184
+ resolve(false);
185
+ });
186
+ wss.on("connection", (ws, req) => {
187
+ if (!req.headers[RELAY_HEADER])
188
+ return this.attach(ws);
189
+ const theirs = Number(req.headers[PROTOCOL_HEADER] ?? 0);
190
+ if (theirs > this.protocol && this.mode === "primary") {
191
+ ws.close(1012, "primary changed");
192
+ void this.stepDown(theirs);
193
+ return;
194
+ }
195
+ this.attachRelay(ws);
196
+ });
197
+ });
198
+ }
199
+ connectRelay() {
200
+ return new Promise((resolve) => {
201
+ const ws = new WebSocket(`ws://${this.host}:${this.port}`, {
202
+ headers: { [RELAY_HEADER]: this.key, [PROTOCOL_HEADER]: String(this.protocol) },
203
+ });
204
+ let settled = false;
205
+ const done = () => (settled ? undefined : ((settled = true), resolve()));
206
+ ws.once("open", () => {
207
+ this.relaySocket = ws;
208
+ this.mode = "relay";
209
+ log(`relay: port ${this.port} is held by another instance — relaying through it`);
210
+ done();
211
+ });
212
+ ws.once("error", () => {
213
+ // e.g. the port is held by an old version that doesn't accept relays
214
+ if (this.mode !== "primary")
215
+ this.mode = "none";
216
+ done();
217
+ });
218
+ ws.on("message", (data) => {
219
+ let msg;
220
+ try {
221
+ msg = JSON.parse(String(data));
222
+ }
223
+ catch {
224
+ return;
225
+ }
226
+ if (msg.type === "relay-status")
227
+ this.remote = { connected: msg.connected, peers: msg.peers, disabled: msg.disabled ?? [] };
228
+ else {
229
+ const p = this.relayPending.get(msg.id);
230
+ if (!p)
231
+ return;
232
+ clearTimeout(p.timer);
233
+ this.relayPending.delete(msg.id);
234
+ if (msg.type === "relay-response")
235
+ p.resolve(msg.res);
236
+ else
237
+ p.reject(new OsnovaError(msg.message));
238
+ }
239
+ });
240
+ ws.on("close", () => {
241
+ if (this.relaySocket === ws) {
242
+ this.relaySocket = undefined;
243
+ this.remote = { connected: false, peers: [], disabled: this.remote.disabled };
244
+ if (this.mode === "relay")
245
+ this.mode = "none";
246
+ for (const [id, p] of this.relayPending) {
247
+ clearTimeout(p.timer);
248
+ p.reject(new OsnovaError("основной экземпляр сервера отключился во время запроса"));
249
+ this.relayPending.delete(id);
250
+ }
251
+ }
252
+ done();
253
+ });
254
+ });
255
+ }
256
+ /** Primary side: serve a relay connection from another MCP instance. */
257
+ attachRelay(ws) {
258
+ this.relays.add(ws);
259
+ this.sendStatus(ws);
260
+ ws.on("message", async (data) => {
261
+ let msg;
262
+ try {
263
+ msg = JSON.parse(String(data));
264
+ }
265
+ catch {
266
+ return;
267
+ }
268
+ if (msg.type === "relay-activity") {
269
+ this.reportActivity(msg.item);
270
+ this.onPlanChanged?.();
271
+ return;
272
+ }
273
+ if (msg.type !== "relay")
274
+ return;
275
+ try {
276
+ const res = await this.dispatchLocal(msg.payload);
277
+ ws.send(JSON.stringify({ type: "relay-response", id: msg.id, res }));
278
+ }
279
+ catch (e) {
280
+ ws.send(JSON.stringify({ type: "relay-error", id: msg.id, message: e.message }));
281
+ }
282
+ });
283
+ ws.on("close", () => this.relays.delete(ws));
284
+ }
285
+ sendStatus(ws) {
286
+ if (ws.readyState !== WebSocket.OPEN)
287
+ return;
288
+ ws.send(JSON.stringify({
289
+ type: "relay-status",
290
+ connected: this.openPeers().length > 0,
291
+ peers: this.openPeers().map((p) => p.label),
292
+ disabled: [...this.disabledLocal],
293
+ }));
294
+ }
295
+ /**
296
+ * Tell the extension what Claude just did (the popup keeps a feed). A relay
297
+ * passes it to the primary, which owns the extension connection.
298
+ */
299
+ reportActivity(item) {
300
+ if (this.mode === "relay") {
301
+ if (this.relaySocket?.readyState === WebSocket.OPEN) {
302
+ this.relaySocket.send(JSON.stringify({ type: "relay-activity", item }));
303
+ }
304
+ return;
305
+ }
306
+ for (const p of this.openPeers())
307
+ p.ws.send(JSON.stringify({ type: "activity", item }));
308
+ }
309
+ broadcastStatus() {
310
+ for (const ws of this.relays)
311
+ this.sendStatus(ws);
312
+ }
313
+ attach(ws) {
314
+ const peer = new Peer(ws);
315
+ this.peers.add(peer);
316
+ ws.on("message", (data) => {
317
+ let msg;
318
+ try {
319
+ msg = JSON.parse(String(data));
320
+ }
321
+ catch {
322
+ return;
323
+ }
324
+ if (msg.type === "hello") {
325
+ peer.version = msg.version;
326
+ peer.browser = msg.browser;
327
+ log(`extension connected: ${peer.label}; connected now: ${this.openPeers().length}`);
328
+ ws.send(JSON.stringify({ type: "server-info", protocol: this.protocol }));
329
+ this.broadcastStatus();
330
+ }
331
+ else if (msg.type === "ping") {
332
+ ws.send(JSON.stringify({ type: "pong" }));
333
+ }
334
+ else if (msg.type === "settings") {
335
+ this.disabledLocal = new Set(Array.isArray(msg.disabled) ? msg.disabled.map(String) : []);
336
+ log(`disabled platforms: ${[...this.disabledLocal].join(", ") || "none"}`);
337
+ this.broadcastStatus();
338
+ }
339
+ else if (msg.type === "get-plan" || msg.type === "account" || msg.type === "free-sites") {
340
+ const send = (m) => ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify(m));
341
+ (this.onPlanMessage?.(msg) ?? Promise.reject(new Error("тарифы недоступны")))
342
+ .then((plan) => send({ type: "plan", plan }))
343
+ .catch((e) => send({ type: "plan", plan: null, error: e.message }));
344
+ }
345
+ else if (msg.type === "check-accounts") {
346
+ const id = msg.id;
347
+ const progress = (result, sites) => {
348
+ if (ws.readyState === WebSocket.OPEN)
349
+ ws.send(JSON.stringify({ type: "account-progress", id, result, sites }));
350
+ };
351
+ (this.onCheckAccounts?.(progress, msg.sites) ?? Promise.reject(new Error("проверка недоступна")))
352
+ .then((results) => ws.send(JSON.stringify({ type: "accounts", id, results })))
353
+ .catch((e) => ws.send(JSON.stringify({ type: "accounts", id, results: [], error: e.message })));
354
+ }
355
+ else if (msg.type === "response" || msg.type === "error") {
356
+ const p = peer.pending.get(msg.id);
357
+ if (!p)
358
+ return;
359
+ clearTimeout(p.timer);
360
+ peer.pending.delete(msg.id);
361
+ if (msg.type === "response")
362
+ p.resolve({ status: msg.status, json: msg.json, ...(msg.headers ? { headers: msg.headers } : {}), ...(msg.url ? { url: msg.url } : {}), ...(msg.via ? { via: msg.via } : {}) });
363
+ else
364
+ p.reject(new OsnovaError(msg.message));
365
+ }
366
+ });
367
+ ws.on("close", () => {
368
+ this.peers.delete(peer);
369
+ this.broadcastStatus();
370
+ for (const [id, p] of peer.pending) {
371
+ clearTimeout(p.timer);
372
+ p.reject(new OsnovaError("расширение отключилось во время запроса"));
373
+ peer.pending.delete(id);
374
+ }
375
+ });
376
+ }
377
+ sendTo(peer, payload) {
378
+ const id = this.nextId++;
379
+ return new Promise((resolve, reject) => {
380
+ const timer = setTimeout(() => {
381
+ peer.pending.delete(id);
382
+ reject(new OsnovaError("расширение не ответило за 90 секунд"));
383
+ }, REQUEST_TIMEOUT_MS);
384
+ peer.pending.set(id, { resolve, reject, timer });
385
+ const msg = "req" in payload ? { type: "request", id, req: payload.req } : { type: "page", id, page: payload.page };
386
+ peer.ws.send(JSON.stringify(msg));
387
+ });
388
+ }
389
+ /** Osnova API call (vc.ru / DTF) with the site's token auth. */
390
+ send(req) {
391
+ return this.dispatch({ req });
392
+ }
393
+ /** Arbitrary fetch from a tab of the site, with the user's cookies. */
394
+ async pageFetch(page) {
395
+ const res = (await this.dispatch({ page }));
396
+ if (process.env.LONGREAD_TRACE)
397
+ log(`page ${page.method ?? "GET"} ${new URL(page.url, page.origin).host}${new URL(page.url, page.origin).pathname} → ${res.status} via ${res.via ?? "?"}`);
398
+ return res;
399
+ }
400
+ /**
401
+ * Wait briefly for a connection: during a primary/relay hand-over or an
402
+ * extension reconnect (every 3 s) there are a few seconds without one.
403
+ */
404
+ async waitConnected(ms = 10_000) {
405
+ const deadline = Date.now() + ms;
406
+ while (!this.connected && Date.now() < deadline) {
407
+ if (this.mode === "none")
408
+ await this.ensureRole();
409
+ await new Promise((r) => setTimeout(r, 250));
410
+ }
411
+ return this.connected;
412
+ }
413
+ async dispatch(payload) {
414
+ await this.waitConnected();
415
+ return this.mode === "relay" ? this.dispatchRelay(payload) : this.dispatchLocal(payload);
416
+ }
417
+ dispatchRelay(payload) {
418
+ const ws = this.relaySocket;
419
+ if (!ws || ws.readyState !== WebSocket.OPEN)
420
+ return Promise.reject(new OsnovaError("нет связи с основным экземпляром сервера"));
421
+ const id = this.nextId++;
422
+ return new Promise((resolve, reject) => {
423
+ const timer = setTimeout(() => {
424
+ this.relayPending.delete(id);
425
+ reject(new OsnovaError("основной экземпляр сервера не ответил за 100 секунд"));
426
+ }, REQUEST_TIMEOUT_MS + 10_000);
427
+ this.relayPending.set(id, { resolve, reject, timer });
428
+ ws.send(JSON.stringify({ type: "relay", id, payload }));
429
+ });
430
+ }
431
+ async dispatchLocal(payload) {
432
+ const peers = this.openPeers();
433
+ if (peers.length === 0)
434
+ throw new OsnovaError("Расширение Tentek Poster не подключено");
435
+ const errors = [];
436
+ for (const peer of peers) {
437
+ try {
438
+ return await this.sendTo(peer, payload);
439
+ }
440
+ catch (e) {
441
+ errors.push(peers.length > 1 ? `${peer.label}: ${e.message}` : e.message);
442
+ }
443
+ }
444
+ throw new OsnovaError(`Расширение: ${errors.join("; ")}`);
445
+ }
446
+ async stop() {
447
+ this.stopped = true;
448
+ clearInterval(this.timer);
449
+ this.relaySocket?.close();
450
+ for (const p of this.peers)
451
+ p.ws.close();
452
+ for (const r of this.relays)
453
+ r.close();
454
+ await new Promise((r) => (this.wss ? this.wss.close(() => r()) : r()));
455
+ this.mode = "none";
456
+ }
457
+ }
package/dist/config.js ADDED
@@ -0,0 +1,63 @@
1
+ import { existsSync, renameSync, symlinkSync } from "node:fs";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ const DEFAULT_DIR = join(homedir(), ".config", "tentek-poster");
6
+ const OLD_DIR = join(homedir(), ".config", "longread-mcp");
7
+ /** Settings, tokens, relay key and local drafts. */
8
+ export const CONFIG_DIR = process.env.TENTEK_POSTER_HOME ?? process.env.LONGREAD_MCP_HOME ?? DEFAULT_DIR;
9
+ // The project used to be called Longread MCP: move its folder once and leave a
10
+ // link behind, so a server from before the rename still finds its files.
11
+ if (CONFIG_DIR === DEFAULT_DIR && !existsSync(DEFAULT_DIR) && existsSync(OLD_DIR)) {
12
+ try {
13
+ renameSync(OLD_DIR, DEFAULT_DIR);
14
+ symlinkSync(DEFAULT_DIR, OLD_DIR);
15
+ }
16
+ catch {
17
+ // Not fatal: the server then starts with a fresh folder.
18
+ }
19
+ }
20
+ async function readJson(path, fallback) {
21
+ try {
22
+ return JSON.parse(await readFile(path, "utf8"));
23
+ }
24
+ catch (e) {
25
+ if (e.code === "ENOENT")
26
+ return fallback;
27
+ throw e;
28
+ }
29
+ }
30
+ let tmpSeq = 0;
31
+ export async function writeJson(path, value) {
32
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
33
+ const tmp = `${path}.${process.pid}.${++tmpSeq}.tmp`; // unique: parallel writes must not share a temp file
34
+ await writeFile(tmp, JSON.stringify(value, null, 2), { mode: 0o600 });
35
+ await rename(tmp, path);
36
+ }
37
+ export const readConfig = () => readJson(join(CONFIG_DIR, "config.json"), {});
38
+ /** Drafts kept on disk for platforms without server-side drafts (Сетка). */
39
+ export class LocalDrafts {
40
+ path;
41
+ constructor(name) {
42
+ this.path = join(CONFIG_DIR, "drafts", `${name}.json`);
43
+ }
44
+ all() {
45
+ return readJson(this.path, {});
46
+ }
47
+ async get(id) {
48
+ return (await this.all())[id];
49
+ }
50
+ async put(id, value) {
51
+ const all = await this.all();
52
+ all[id] = { ...value, updatedAt: new Date().toISOString() };
53
+ await writeJson(this.path, all);
54
+ }
55
+ async remove(id) {
56
+ const all = await this.all();
57
+ delete all[id];
58
+ await writeJson(this.path, all);
59
+ }
60
+ get file() {
61
+ return this.path;
62
+ }
63
+ }