@aronnaxlin/bgm-cli 1.0.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.
Files changed (46) hide show
  1. package/LICENSE +660 -0
  2. package/README.en.md +122 -0
  3. package/README.md +127 -0
  4. package/README.zh-TW.md +122 -0
  5. package/package.json +41 -0
  6. package/src/cli.js +993 -0
  7. package/src/commands/blog.js +213 -0
  8. package/src/commands/calendar.js +32 -0
  9. package/src/commands/character.js +291 -0
  10. package/src/commands/collection.js +418 -0
  11. package/src/commands/episode.js +379 -0
  12. package/src/commands/group.js +488 -0
  13. package/src/commands/index.js +362 -0
  14. package/src/commands/notify.js +74 -0
  15. package/src/commands/person.js +297 -0
  16. package/src/commands/status.js +74 -0
  17. package/src/commands/subject.js +537 -0
  18. package/src/commands/timeline.js +288 -0
  19. package/src/commands/trending.js +58 -0
  20. package/src/commands/tui.js +1537 -0
  21. package/src/commands/user.js +83 -0
  22. package/src/core/client.js +2065 -0
  23. package/src/core/config.js +450 -0
  24. package/src/core/http.js +144 -0
  25. package/src/core/output.js +3888 -0
  26. package/src/core/proxy.js +47 -0
  27. package/src/core/reactions.js +62 -0
  28. package/src/core/turnstile.js +526 -0
  29. package/src/data/bangumi-emotes.json +311 -0
  30. package/src/utils/args.js +113 -0
  31. package/src/utils/auth-flow.js +373 -0
  32. package/src/utils/auth.js +90 -0
  33. package/src/utils/calendar.js +23 -0
  34. package/src/utils/collection-ops.js +333 -0
  35. package/src/utils/collection.js +240 -0
  36. package/src/utils/formatters.js +157 -0
  37. package/src/utils/helpers.js +283 -0
  38. package/src/utils/hot.js +182 -0
  39. package/src/utils/install.js +40 -0
  40. package/src/utils/prompts.js +87 -0
  41. package/src/utils/relay.js +74 -0
  42. package/src/utils/status.js +68 -0
  43. package/src/utils/tui-interactive.js +197 -0
  44. package/src/utils/tui-render.js +86 -0
  45. package/src/utils/turnstile-flow.js +154 -0
  46. package/src/utils/validators.js +412 -0
@@ -0,0 +1,47 @@
1
+ import { ProxyAgent, setGlobalDispatcher } from "undici";
2
+
3
+ let installedProxy = null;
4
+
5
+ export function resolveProxyUrl(config) {
6
+ const fromConfig = typeof config?.proxy === "string" ? config.proxy.trim() : "";
7
+ if (fromConfig) {
8
+ return { url: fromConfig, source: "config" };
9
+ }
10
+
11
+ const envCandidates = [
12
+ ["BGM_PROXY", process.env.BGM_PROXY],
13
+ ["HTTPS_PROXY", process.env.HTTPS_PROXY],
14
+ ["https_proxy", process.env.https_proxy],
15
+ ["HTTP_PROXY", process.env.HTTP_PROXY],
16
+ ["http_proxy", process.env.http_proxy],
17
+ ];
18
+
19
+ for (const [name, value] of envCandidates) {
20
+ if (typeof value === "string" && value.trim() !== "") {
21
+ return { url: value.trim(), source: `env:${name}` };
22
+ }
23
+ }
24
+
25
+ return { url: "", source: "none" };
26
+ }
27
+
28
+ export function installProxyFromConfig(config) {
29
+ const { url, source } = resolveProxyUrl(config);
30
+ if (!url) {
31
+ installedProxy = null;
32
+ return null;
33
+ }
34
+
35
+ try {
36
+ setGlobalDispatcher(new ProxyAgent(url));
37
+ installedProxy = { url, source };
38
+ return installedProxy;
39
+ } catch (error) {
40
+ installedProxy = null;
41
+ throw new Error(`Failed to install proxy ${url}: ${error?.message ?? error}`);
42
+ }
43
+ }
44
+
45
+ export function getInstalledProxy() {
46
+ return installedProxy;
47
+ }
@@ -0,0 +1,62 @@
1
+ import { CommandError } from "./output.js";
2
+
3
+ const TOPIC_POST_REACTION_VALUES = Object.freeze([54, 62, 79, 80, 85, 88, 90, 104, 122, 140]);
4
+ const SUBJECT_COLLECT_REACTION_VALUES = Object.freeze([54]);
5
+
6
+ export const BANGUMI_REACTION_TARGETS = Object.freeze({
7
+ subjectPost: Object.freeze({
8
+ label: "subject discussion reply",
9
+ allowedValues: TOPIC_POST_REACTION_VALUES,
10
+ note: "Subject and group topic replies share the p1 topic-post reaction shape; values were probed on a group topic post.",
11
+ }),
12
+ groupPost: Object.freeze({
13
+ label: "group topic reply",
14
+ allowedValues: TOPIC_POST_REACTION_VALUES,
15
+ note: "Values probed live on a group topic post.",
16
+ }),
17
+ episodeComment: Object.freeze({
18
+ label: "episode comment",
19
+ allowedValues: TOPIC_POST_REACTION_VALUES,
20
+ note: "Accepted values are inferred from the same p1 reaction set as topic posts; re-check if Bangumi changes the behavior.",
21
+ }),
22
+ subjectCollect: Object.freeze({
23
+ label: "subject collection comment",
24
+ allowedValues: SUBJECT_COLLECT_REACTION_VALUES,
25
+ note: "Value 54 is probed valid; 79 is probed invalid for this target.",
26
+ }),
27
+ timeline: Object.freeze({
28
+ label: "timeline entry",
29
+ allowedValues: TOPIC_POST_REACTION_VALUES,
30
+ note: "Accepted values are inferred from the same p1 reaction set as topic posts; re-check if Bangumi changes the behavior.",
31
+ }),
32
+ });
33
+
34
+ export function normalizeBangumiReactionValue(value, targetKey) {
35
+ if (value === undefined || value === null || value === "") {
36
+ return undefined;
37
+ }
38
+
39
+ const parsed = Number.parseInt(String(value), 10);
40
+ if (Number.isNaN(parsed)) {
41
+ throw new CommandError(`Expected reaction value to be an integer, received: ${value}`);
42
+ }
43
+ if (parsed <= 0) {
44
+ throw new CommandError(`Expected reaction value to be > 0, received: ${value}`);
45
+ }
46
+
47
+ const target = BANGUMI_REACTION_TARGETS[targetKey];
48
+ if (!target) {
49
+ return parsed;
50
+ }
51
+
52
+ const allowedValues = target.allowedValues;
53
+ if (Array.isArray(allowedValues) && !allowedValues.includes(parsed)) {
54
+ throw new CommandError([
55
+ `Unsupported reaction value ${parsed} for ${target.label}.`,
56
+ `Known supported values: ${allowedValues.join(", ")}.`,
57
+ "Bangumi only accepts a subset of site emotes as reaction stickers.",
58
+ ].join(" "));
59
+ }
60
+
61
+ return parsed;
62
+ }
@@ -0,0 +1,526 @@
1
+ import http from "node:http";
2
+ import { randomUUID } from "node:crypto";
3
+ import { CommandError } from "./output.js";
4
+
5
+ export const TURNSTILE_SITE_KEY = "0x4AAAAAAABkMYinukE8nzYS";
6
+ export const DEFAULT_TURNSTILE_TIMEOUT_MS = 300000;
7
+ export const TURNSTILE_MANUAL_PAGE_URL = "https://next.bgm.tv/";
8
+ export const TURNSTILE_MANUAL_DOC_PATH = "docs/research/turnstile-manual-token.zh-CN.md";
9
+
10
+ export async function startTurnstileFlow(options = {}) {
11
+ const listenHost = normalizeListenHost(options.listenHost);
12
+ const requestedPort = normalizePort(options.port);
13
+ const timeoutMs = normalizeTimeoutMs(options.timeoutMs);
14
+ const state = randomUUID();
15
+ let timeout = null;
16
+ let settled = false;
17
+ let resolveToken;
18
+ let rejectToken;
19
+
20
+ const completion = new Promise((resolve, reject) => {
21
+ resolveToken = resolve;
22
+ rejectToken = reject;
23
+ });
24
+
25
+ const server = http.createServer(async (req, res) => {
26
+ try {
27
+ const requestUrl = new URL(req.url ?? "/", origin);
28
+
29
+ if (req.method === "GET" && requestUrl.pathname === "/") {
30
+ res.writeHead(302, {
31
+ Location: verificationPath,
32
+ });
33
+ res.end();
34
+ return;
35
+ }
36
+
37
+ if (req.method === "GET" && requestUrl.pathname === "/turnstile") {
38
+ if (requestUrl.searchParams.get("state") !== state) {
39
+ respondHtml(res, 400, "Invalid state", "<h1>Invalid state</h1><p>This verification link is no longer valid.</p>");
40
+ return;
41
+ }
42
+
43
+ respondHtml(
44
+ res,
45
+ 200,
46
+ "Turnstile helper",
47
+ renderTurnstilePage({
48
+ state,
49
+ callbackUrl: `${origin}/callback`,
50
+ actionLabel: options.actionLabel,
51
+ }),
52
+ );
53
+ return;
54
+ }
55
+
56
+ if (req.method === "OPTIONS" && requestUrl.pathname === "/callback") {
57
+ respondCallbackPreflight(req, res);
58
+ return;
59
+ }
60
+
61
+ if (req.method === "POST" && requestUrl.pathname === "/callback") {
62
+ const body = await readJsonBody(req);
63
+ if (body.state !== state) {
64
+ respondCallbackJson(req, res, 400, { error: "invalid_state" });
65
+ return;
66
+ }
67
+
68
+ const token = typeof body.token === "string" ? body.token.trim() : "";
69
+ if (!token) {
70
+ respondCallbackJson(req, res, 400, { error: "missing_token" });
71
+ return;
72
+ }
73
+
74
+ respondCallbackJson(req, res, 200, {
75
+ ok: true,
76
+ message: "Token received. You can return to the terminal.",
77
+ });
78
+ finishResolve({
79
+ token,
80
+ tokenPreview: previewToken(token),
81
+ verificationUrl,
82
+ listenHost,
83
+ port,
84
+ });
85
+ return;
86
+ }
87
+
88
+ if (req.method === "GET" && requestUrl.pathname === "/health") {
89
+ respondJson(res, 200, { ok: true });
90
+ return;
91
+ }
92
+
93
+ respondHtml(res, 404, "Not Found", "<h1>Not Found</h1>");
94
+ } catch (error) {
95
+ finishReject(error);
96
+ respondJson(res, 500, { error: "internal_error" });
97
+ }
98
+ });
99
+
100
+ await new Promise((resolve, reject) => {
101
+ const onListenError = (error) => {
102
+ reject(new CommandError(`Failed to start Turnstile helper on ${listenHost}:${requestedPort}: ${error.message}`));
103
+ };
104
+
105
+ server.once("error", onListenError);
106
+ server.listen(requestedPort, listenHost, () => resolve());
107
+ server.once("listening", () => {
108
+ server.off("error", onListenError);
109
+ });
110
+ }).catch((error) => {
111
+ throw error instanceof CommandError
112
+ ? error
113
+ : new CommandError(`Failed to start Turnstile helper on ${listenHost}:${requestedPort}: ${error.message}`);
114
+ });
115
+
116
+ const address = server.address();
117
+ if (!address || typeof address === "string") {
118
+ server.close();
119
+ throw new CommandError("Failed to determine Turnstile helper listen address.");
120
+ }
121
+
122
+ const port = address.port;
123
+ const origin = normalizePublicOrigin(options.publicOrigin, listenHost, port);
124
+ const verificationPath = `/turnstile?state=${encodeURIComponent(state)}`;
125
+ const verificationUrl = `${origin}${verificationPath}`;
126
+
127
+ timeout = setTimeout(() => {
128
+ finishReject(new CommandError("Timed out waiting for Turnstile verification."));
129
+ }, timeoutMs);
130
+
131
+ server.on("error", (error) => {
132
+ finishReject(new CommandError(`Turnstile helper failed: ${error.message}`));
133
+ });
134
+
135
+ return {
136
+ verificationUrl,
137
+ listenHost,
138
+ port,
139
+ timeoutMs,
140
+ close: cleanup,
141
+ completion,
142
+ };
143
+
144
+ function cleanup() {
145
+ clearTimeout(timeout);
146
+ server.close();
147
+ }
148
+
149
+ function finishResolve(value) {
150
+ if (settled) {
151
+ return;
152
+ }
153
+ settled = true;
154
+ cleanup();
155
+ resolveToken(value);
156
+ }
157
+
158
+ function finishReject(error) {
159
+ if (settled) {
160
+ return;
161
+ }
162
+ settled = true;
163
+ cleanup();
164
+ rejectToken(error);
165
+ }
166
+ }
167
+
168
+ function normalizeListenHost(value) {
169
+ const host = String(value ?? "127.0.0.1").trim();
170
+ return host || "127.0.0.1";
171
+ }
172
+
173
+ function normalizePort(value) {
174
+ if (value === undefined || value === null || value === "") {
175
+ return 0;
176
+ }
177
+
178
+ const parsed = Number.parseInt(String(value), 10);
179
+ if (Number.isNaN(parsed) || parsed < 0 || parsed > 65535) {
180
+ throw new CommandError(`Expected port to be between 0 and 65535, received: ${value}`);
181
+ }
182
+ return parsed;
183
+ }
184
+
185
+ function normalizeTimeoutMs(value) {
186
+ if (value === undefined || value === null || value === "") {
187
+ return DEFAULT_TURNSTILE_TIMEOUT_MS;
188
+ }
189
+
190
+ const parsed = Number.parseInt(String(value), 10);
191
+ if (Number.isNaN(parsed) || parsed <= 0) {
192
+ throw new CommandError(`Expected timeout to be > 0, received: ${value}`);
193
+ }
194
+ return parsed;
195
+ }
196
+
197
+ function normalizePublicOrigin(publicOrigin, listenHost, port) {
198
+ if (publicOrigin !== undefined && publicOrigin !== null && publicOrigin !== "") {
199
+ const url = new URL(String(publicOrigin));
200
+ return String(url).replace(/\/$/, "");
201
+ }
202
+
203
+ const host = ["0.0.0.0", "::"].includes(listenHost) ? "127.0.0.1" : listenHost;
204
+ return `http://${host}:${port}`;
205
+ }
206
+
207
+ async function readJsonBody(req) {
208
+ const chunks = [];
209
+ let size = 0;
210
+
211
+ for await (const chunk of req) {
212
+ size += chunk.length;
213
+ if (size > 64 * 1024) {
214
+ throw new CommandError("Turnstile callback body is too large.");
215
+ }
216
+ chunks.push(chunk);
217
+ }
218
+
219
+ const raw = Buffer.concat(chunks).toString("utf8");
220
+ if (!raw) {
221
+ return {};
222
+ }
223
+
224
+ try {
225
+ return JSON.parse(raw);
226
+ } catch {
227
+ throw new CommandError("Turnstile callback payload is not valid JSON.");
228
+ }
229
+ }
230
+
231
+ function renderTurnstilePage({ state, actionLabel, callbackUrl }) {
232
+ const normalizedActionLabel = actionLabel ? String(actionLabel) : "complete the next write operation";
233
+ const consoleScript = buildTurnstileConsoleScript({
234
+ state,
235
+ callbackUrl,
236
+ });
237
+
238
+ return `
239
+ <html>
240
+ <head>
241
+ <meta charset="utf-8" />
242
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
243
+ <title>Bangumi Turnstile Helper</title>
244
+ <style>
245
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; margin: 40px auto; max-width: 880px; padding: 0 16px; line-height: 1.6; color: #1f2937; }
246
+ .card { border: 1px solid #d1d5db; border-radius: 12px; padding: 24px; }
247
+ h1 { font-size: 24px; margin-top: 0; }
248
+ .muted { color: #6b7280; }
249
+ .actions { display: flex; gap: 12px; flex-wrap: wrap; margin: 16px 0; }
250
+ .button, button { appearance: none; border: 1px solid #2563eb; background: #2563eb; color: white; border-radius: 10px; padding: 10px 14px; cursor: pointer; font: inherit; text-decoration: none; }
251
+ .button.secondary, button.secondary { background: white; color: #2563eb; }
252
+ textarea { width: 100%; min-height: 220px; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; border: 1px solid #d1d5db; border-radius: 10px; padding: 12px; box-sizing: border-box; }
253
+ #tokenInput { min-height: 110px; }
254
+ #status { margin-top: 16px; font-weight: 600; }
255
+ #details { margin-top: 8px; color: #374151; white-space: pre-wrap; }
256
+ code { background: #f3f4f6; padding: 2px 6px; border-radius: 6px; }
257
+ ol { padding-left: 20px; }
258
+ </style>
259
+ </head>
260
+ <body>
261
+ <div class="card">
262
+ <h1>Bangumi Turnstile Helper</h1>
263
+ <p>bgm-cli needs a short-lived <code>turnstileToken</code> to ${escapeHtml(normalizedActionLabel)}.</p>
264
+ <p class="muted">This helper page does not try to run Turnstile on localhost. Instead, it helps you run the verification inside the real <code>${TURNSTILE_MANUAL_PAGE_URL}</code> page context and send the token back to bgm-cli.</p>
265
+ <ol>
266
+ <li>Click <strong>Open next.bgm.tv</strong>.</li>
267
+ <li>Open DevTools Console on that page.</li>
268
+ <li>Click <strong>Copy console script</strong> on this helper page, then paste it into Console and press Enter.</li>
269
+ <li>Complete the Turnstile widget shown on <code>next.bgm.tv</code>.</li>
270
+ <li>If bgm-cli does not continue automatically, paste the token into the fallback box below and submit it manually.</li>
271
+ </ol>
272
+ <div class="actions">
273
+ <a class="button" href="${TURNSTILE_MANUAL_PAGE_URL}" target="_blank" rel="noreferrer">Open next.bgm.tv</a>
274
+ <button class="secondary" type="button" id="copyScriptButton">Copy console script</button>
275
+ <a class="button secondary" href="${TURNSTILE_MANUAL_PAGE_URL}" target="_blank" rel="noreferrer">Open page again</a>
276
+ </div>
277
+ <label for="scriptBox"><strong>Console script</strong></label>
278
+ <textarea id="scriptBox" readonly>${escapeHtml(consoleScript)}</textarea>
279
+ <div class="actions">
280
+ <button type="button" id="submitTokenButton">Submit token manually</button>
281
+ </div>
282
+ <label for="tokenInput"><strong>Fallback: paste a token manually</strong></label>
283
+ <textarea id="tokenInput" placeholder="Paste turnstileToken here if automatic submission from next.bgm.tv fails"></textarea>
284
+ <div id="status">Waiting for a Turnstile token...</div>
285
+ <div id="details" class="muted"></div>
286
+ </div>
287
+ <script>
288
+ const state = ${JSON.stringify(state)};
289
+ const callbackUrl = ${JSON.stringify(callbackUrl)};
290
+ const docsPath = ${JSON.stringify(TURNSTILE_MANUAL_DOC_PATH)};
291
+ const scriptText = ${JSON.stringify(consoleScript)};
292
+
293
+ function setStatus(title, detail) {
294
+ const status = document.getElementById('status');
295
+ const details = document.getElementById('details');
296
+ status.textContent = title;
297
+ details.textContent = detail || '';
298
+ }
299
+
300
+ document.getElementById('scriptBox').value = scriptText;
301
+
302
+ document.getElementById('copyScriptButton').addEventListener('click', async () => {
303
+ try {
304
+ await navigator.clipboard.writeText(scriptText);
305
+ setStatus('Console script copied.', 'Switch to next.bgm.tv, paste the script into DevTools Console, and complete the Turnstile check.');
306
+ } catch {
307
+ const textarea = document.getElementById('scriptBox');
308
+ textarea.focus();
309
+ textarea.select();
310
+ setStatus('Clipboard copy failed.', 'The script text has been selected. Copy it manually, then paste it into DevTools Console on next.bgm.tv.');
311
+ }
312
+ });
313
+
314
+ async function submitToken(token, source) {
315
+ const trimmed = String(token || '').trim();
316
+ if (!trimmed) {
317
+ setStatus('Token required.', 'Paste a non-empty turnstileToken, then submit again.');
318
+ return;
319
+ }
320
+
321
+ setStatus('Submitting token to bgm-cli...', '');
322
+
323
+ try {
324
+ const response = await fetch(callbackUrl, {
325
+ method: 'POST',
326
+ mode: 'cors',
327
+ headers: { 'Content-Type': 'application/json' },
328
+ body: JSON.stringify({ token: trimmed, state, source }),
329
+ });
330
+ const payload = await response.json().catch(() => ({}));
331
+ if (!response.ok) {
332
+ throw new Error(payload.error || 'verification_failed');
333
+ }
334
+ setStatus('Token submitted.', payload.message || 'bgm-cli should continue automatically now.');
335
+ } catch (error) {
336
+ setStatus(
337
+ 'Automatic submission failed.',
338
+ (error && error.message ? error.message : 'unknown_error') + '\\n\\nKeep the token and submit it again manually, or rerun the command. See ' + docsPath,
339
+ );
340
+ }
341
+ }
342
+
343
+ document.getElementById('submitTokenButton').addEventListener('click', () => {
344
+ submitToken(document.getElementById('tokenInput').value, 'helper-page');
345
+ });
346
+
347
+ setStatus('Waiting for a Turnstile token...', 'Open next.bgm.tv, run the copied script, and complete the Turnstile check. If automatic submission fails, paste the token here manually.');
348
+ </script>
349
+ </body>
350
+ </html>
351
+ `;
352
+ }
353
+
354
+ function buildTurnstileConsoleScript({ state, callbackUrl }) {
355
+ return `(() => {
356
+ const callbackUrl = ${JSON.stringify(callbackUrl)};
357
+ const state = ${JSON.stringify(state)};
358
+ const sitekey = ${JSON.stringify(TURNSTILE_SITE_KEY)};
359
+
360
+ function log(message, ...rest) {
361
+ console.log('[bgm-cli]', message, ...rest);
362
+ }
363
+
364
+ function waitForTurnstile() {
365
+ if (window.turnstile) return Promise.resolve();
366
+ let script = document.querySelector('script[src*="challenges.cloudflare.com/turnstile"]');
367
+ if (!script) {
368
+ script = document.createElement('script');
369
+ script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
370
+ script.async = true;
371
+ script.defer = true;
372
+ document.head.appendChild(script);
373
+ }
374
+
375
+ return new Promise((resolve, reject) => {
376
+ const startedAt = Date.now();
377
+ const timer = setInterval(() => {
378
+ if (window.turnstile) {
379
+ clearInterval(timer);
380
+ resolve();
381
+ return;
382
+ }
383
+ if (Date.now() - startedAt > 10000) {
384
+ clearInterval(timer);
385
+ reject(new Error('turnstile did not become available'));
386
+ }
387
+ }, 100);
388
+ });
389
+ }
390
+
391
+ function ensureContainer() {
392
+ const old = document.getElementById('bgm-cli-turnstile-box');
393
+ if (old) old.remove();
394
+
395
+ const box = document.createElement('div');
396
+ box.id = 'bgm-cli-turnstile-box';
397
+ box.style.cssText = [
398
+ 'position:fixed',
399
+ 'right:16px',
400
+ 'bottom:16px',
401
+ 'z-index:2147483647',
402
+ 'width:360px',
403
+ 'padding:16px',
404
+ 'background:#fff',
405
+ 'color:#111827',
406
+ 'border:1px solid #d1d5db',
407
+ 'border-radius:12px',
408
+ 'box-shadow:0 12px 32px rgba(0,0,0,.2)',
409
+ 'font:14px/1.5 -apple-system, BlinkMacSystemFont, sans-serif'
410
+ ].join(';');
411
+ box.innerHTML = [
412
+ '<div style="font-weight:700;margin-bottom:8px">bgm-cli Turnstile Helper<\/div>',
413
+ '<div style="margin-bottom:8px">Complete the verification below. bgm-cli will try to receive the token automatically.<\/div>',
414
+ '<div id="bgm-cli-turnstile-widget"><\/div>',
415
+ '<div id="bgm-cli-turnstile-status" style="margin-top:10px;color:#4b5563">Waiting for verification...<\/div>'
416
+ ].join('');
417
+ document.body.appendChild(box);
418
+ return box;
419
+ }
420
+
421
+ async function submitToken(token, box) {
422
+ window.__bgmCliTurnstileToken = token;
423
+ const status = box.querySelector('#bgm-cli-turnstile-status');
424
+ status.textContent = 'Submitting token back to bgm-cli...';
425
+
426
+ try {
427
+ const response = await fetch(callbackUrl, {
428
+ method: 'POST',
429
+ mode: 'cors',
430
+ headers: { 'Content-Type': 'application/json' },
431
+ body: JSON.stringify({ token, state, source: 'next.bgm.tv-console' }),
432
+ });
433
+
434
+ if (!response.ok) {
435
+ throw new Error('local helper rejected the token with status ' + response.status);
436
+ }
437
+
438
+ status.textContent = 'Token sent to bgm-cli. You can return to the terminal.';
439
+ log('turnstile token submitted to bgm-cli automatically');
440
+ return;
441
+ } catch (error) {
442
+ status.textContent = 'Auto-submit failed. Copy the token from console and paste it into the helper page.';
443
+ log('auto-submit failed:', error);
444
+ log('turnstile token:', token);
445
+ log('copy with: copy(window.__bgmCliTurnstileToken)');
446
+ }
447
+ }
448
+
449
+ waitForTurnstile().then(() => {
450
+ const box = ensureContainer();
451
+ window.__bgmCliTurnstileToken = '';
452
+ window.turnstile.render('#bgm-cli-turnstile-widget', {
453
+ sitekey,
454
+ theme: 'auto',
455
+ callback(token) {
456
+ submitToken(token, box);
457
+ },
458
+ 'error-callback'(code) {
459
+ box.querySelector('#bgm-cli-turnstile-status').textContent = 'Turnstile error: ' + code;
460
+ log('turnstile error:', code);
461
+ },
462
+ 'expired-callback'() {
463
+ box.querySelector('#bgm-cli-turnstile-status').textContent = 'Token expired. Re-run the script if needed.';
464
+ log('turnstile token expired');
465
+ },
466
+ });
467
+ }).catch((error) => {
468
+ log('failed to initialize turnstile helper:', error);
469
+ });
470
+ })();`;
471
+ }
472
+
473
+ function respondHtml(res, statusCode, statusMessage, body) {
474
+ res.writeHead(statusCode, statusMessage, {
475
+ "Content-Type": "text/html; charset=utf-8",
476
+ });
477
+ res.end(`<!doctype html>${body}`);
478
+ }
479
+
480
+ function respondJson(res, statusCode, payload) {
481
+ res.writeHead(statusCode, {
482
+ "Content-Type": "application/json; charset=utf-8",
483
+ });
484
+ res.end(JSON.stringify(payload));
485
+ }
486
+
487
+ function respondCallbackPreflight(req, res) {
488
+ res.writeHead(204, buildCallbackCorsHeaders(req));
489
+ res.end();
490
+ }
491
+
492
+ function respondCallbackJson(req, res, statusCode, payload) {
493
+ res.writeHead(statusCode, {
494
+ "Content-Type": "application/json; charset=utf-8",
495
+ ...buildCallbackCorsHeaders(req),
496
+ });
497
+ res.end(JSON.stringify(payload));
498
+ }
499
+
500
+ function buildCallbackCorsHeaders(req) {
501
+ const requestOrigin = typeof req.headers.origin === "string" ? req.headers.origin : "*";
502
+ return {
503
+ "Access-Control-Allow-Origin": requestOrigin,
504
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
505
+ "Access-Control-Allow-Headers": "Content-Type",
506
+ "Access-Control-Allow-Private-Network": "true",
507
+ Vary: "Origin",
508
+ };
509
+ }
510
+
511
+ function escapeHtml(value) {
512
+ return String(value ?? "")
513
+ .replaceAll("&", "&amp;")
514
+ .replaceAll("<", "&lt;")
515
+ .replaceAll(">", "&gt;")
516
+ .replaceAll('"', "&quot;")
517
+ .replaceAll("'", "&#39;");
518
+ }
519
+
520
+ function previewToken(token) {
521
+ const value = String(token ?? "");
522
+ if (value.length <= 10) {
523
+ return value;
524
+ }
525
+ return `${value.slice(0, 6)}...${value.slice(-4)}`;
526
+ }