@wirecat/tg-cli 0.98.0 → 0.100.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 (113) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/tg.js +23 -28
  3. package/dist/bundle/adapter-2LVPMFKF.js +2790 -0
  4. package/dist/bundle/all-profiles-BLTK2AAB.js +255 -0
  5. package/dist/bundle/anthropic-RJE4XEOO.js +71 -0
  6. package/dist/bundle/bot-api-4XM3NVWG.js +39793 -0
  7. package/dist/bundle/bot-history-WVM5GEQN.js +167 -0
  8. package/dist/bundle/bun-UZXO2LRQ.js +169 -0
  9. package/dist/bundle/bun-sqlite-GJLGSQIT.js +70 -0
  10. package/dist/bundle/chunk-2IM4M7Q2.js +98 -0
  11. package/dist/bundle/chunk-2MXQ2EUN.js +1344 -0
  12. package/dist/bundle/chunk-2XUGPE5W.js +73 -0
  13. package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
  14. package/dist/bundle/chunk-3MVHRZWR.js +2 -0
  15. package/dist/bundle/chunk-3N6LXAPE.js +724 -0
  16. package/dist/bundle/chunk-3QDPV34J.js +6668 -0
  17. package/dist/bundle/chunk-3S5CL55R.js +100 -0
  18. package/dist/bundle/chunk-4U7QOFDA.js +33511 -0
  19. package/dist/bundle/chunk-4VBDVZNE.js +524 -0
  20. package/dist/bundle/chunk-4YCLWWZ3.js +277 -0
  21. package/dist/bundle/chunk-66E5QDLH.js +24 -0
  22. package/dist/bundle/chunk-6VEOR6GD.js +166 -0
  23. package/dist/bundle/chunk-6YLT4YVJ.js +45 -0
  24. package/dist/bundle/chunk-7BFO3DY6.js +21 -0
  25. package/dist/bundle/chunk-A7OBVRJV.js +738 -0
  26. package/dist/bundle/chunk-AFV74GK3.js +50 -0
  27. package/dist/bundle/chunk-ASDZHG5I.js +25 -0
  28. package/dist/bundle/chunk-ATZ44Z77.js +3253 -0
  29. package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
  30. package/dist/bundle/chunk-BAIZAZ6Q.js +82 -0
  31. package/dist/bundle/chunk-BJG6JA5U.js +35 -0
  32. package/dist/bundle/chunk-BL36RR34.js +285 -0
  33. package/dist/bundle/chunk-BZANDKWT.js +71 -0
  34. package/dist/bundle/chunk-CV5ASHTW.js +8170 -0
  35. package/dist/bundle/chunk-DN4QUTWU.js +78 -0
  36. package/dist/bundle/chunk-DVOUKGFK.js +1950 -0
  37. package/dist/bundle/chunk-GTURDJJD.js +570 -0
  38. package/dist/bundle/chunk-GYEOQS2D.js +2795 -0
  39. package/dist/bundle/chunk-H3X5LS6U.js +153 -0
  40. package/dist/bundle/chunk-HKT5EOT5.js +6848 -0
  41. package/dist/bundle/chunk-HXTTDIL7.js +82 -0
  42. package/dist/bundle/chunk-I6WZJVRT.js +1123 -0
  43. package/dist/bundle/chunk-JFJVS5JC.js +41 -0
  44. package/dist/bundle/chunk-JSKT5UZX.js +2315 -0
  45. package/dist/bundle/chunk-KE6L2UEG.js +3068 -0
  46. package/dist/bundle/chunk-LI7TXFLS.js +122 -0
  47. package/dist/bundle/chunk-MQNFEVAH.js +58 -0
  48. package/dist/bundle/chunk-MUEXF4ME.js +582 -0
  49. package/dist/bundle/chunk-OOOV3JBZ.js +35527 -0
  50. package/dist/bundle/chunk-OW3COBN5.js +1275 -0
  51. package/dist/bundle/chunk-P26LWFNZ.js +35 -0
  52. package/dist/bundle/chunk-Q26JMPBP.js +215 -0
  53. package/dist/bundle/chunk-QU2FJMFB.js +18282 -0
  54. package/dist/bundle/chunk-QY3YOOTP.js +18 -0
  55. package/dist/bundle/chunk-RDQMV6EU.js +46 -0
  56. package/dist/bundle/chunk-RER6DAHP.js +3514 -0
  57. package/dist/bundle/chunk-SGJYU3SB.js +54 -0
  58. package/dist/bundle/chunk-SMJTL5U7.js +117 -0
  59. package/dist/bundle/chunk-SYPL4PHV.js +76 -0
  60. package/dist/bundle/chunk-THVNP6S6.js +31 -0
  61. package/dist/bundle/chunk-U7LXA4SO.js +1007 -0
  62. package/dist/bundle/chunk-UD4DOZCN.js +886 -0
  63. package/dist/bundle/chunk-UMLPXNJI.js +63 -0
  64. package/dist/bundle/chunk-V4JSVH4M.js +190 -0
  65. package/dist/bundle/chunk-WE3LBRMB.js +2374 -0
  66. package/dist/bundle/chunk-WKOY3POD.js +452 -0
  67. package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
  68. package/dist/bundle/chunk-YG7PNCSW.js +230 -0
  69. package/dist/bundle/chunk-Z2FHEIXN.js +63 -0
  70. package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
  71. package/dist/bundle/command-contract-AIVKJYIR.js +31 -0
  72. package/dist/bundle/dist-RJMT44PL.js +7577 -0
  73. package/dist/bundle/echarts-YHSYUWLY.js +42501 -0
  74. package/dist/bundle/embed-3HGI2XIW.js +35 -0
  75. package/dist/bundle/embedder-2CJMZETJ.js +108 -0
  76. package/dist/bundle/entry-UVE53OV3.js +14 -0
  77. package/dist/bundle/first-run-6GYC2QS3.js +24 -0
  78. package/dist/bundle/first-screen-HRRLVLOG.js +29 -0
  79. package/dist/bundle/identity-HEV5E57G.js +11 -0
  80. package/dist/bundle/instructions-5UVAXSQV.js +9 -0
  81. package/dist/bundle/mcp-NWXBVNUA.js +165 -0
  82. package/dist/bundle/node-IUL5HSYI.js +2340 -0
  83. package/dist/bundle/node-UPPL626U.js +21 -0
  84. package/dist/bundle/node-YHYEGYVE.js +176 -0
  85. package/dist/bundle/node-sqlite-CQ33A3R2.js +46 -0
  86. package/dist/bundle/oauth-OB3JFAD7.js +18 -0
  87. package/dist/bundle/open-JHGZIXU2.js +20 -0
  88. package/dist/bundle/process-PSKS3N5B.js +91 -0
  89. package/dist/bundle/program-RPYVPNRX.js +1060 -0
  90. package/dist/bundle/prompt-7BXUMJGG.js +13 -0
  91. package/dist/bundle/proxy-transport-3EEMW2HW.js +17 -0
  92. package/dist/bundle/recognize-YMZPL47R.js +191 -0
  93. package/dist/bundle/remote-LQ3Q22NG.js +26 -0
  94. package/dist/bundle/rerank-SM7IYVXJ.js +49 -0
  95. package/dist/bundle/serve-GHUEP5H5.js +181 -0
  96. package/dist/bundle/server-A45HVXQY.js +178 -0
  97. package/dist/bundle/server-K2BQPPHN.js +785 -0
  98. package/dist/bundle/state-WIOL52GZ.js +30 -0
  99. package/dist/bundle/store-XE5AKUJZ.js +121 -0
  100. package/dist/bundle/store-maintenance-command-YS5E7VUN.js +46 -0
  101. package/dist/bundle/tg.js +40 -0
  102. package/dist/commands/context.d.ts.map +1 -1
  103. package/dist/commands/context.js +3 -2
  104. package/dist/commands/context.js.map +1 -1
  105. package/dist/telegram/errors.d.ts.map +1 -1
  106. package/dist/telegram/errors.js +1 -1
  107. package/dist/telegram/errors.js.map +1 -1
  108. package/dist/version.d.ts +1 -1
  109. package/dist/version.d.ts.map +1 -1
  110. package/dist/version.js +1 -1
  111. package/dist/version.js.map +1 -1
  112. package/package.json +5 -3
  113. package/skills/tg-cli/SKILL.md +2 -1
@@ -0,0 +1,82 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ CliError
5
+ } from "./chunk-WE3LBRMB.js";
6
+ import {
7
+ __name
8
+ } from "./chunk-AFV74GK3.js";
9
+
10
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/cli/input-policy.js
11
+ var MAX_BUFFERED_INPUT = 16 * 1024 * 1024;
12
+ var MAX_SECRET_INPUT = 64 * 1024;
13
+ var policies = /* @__PURE__ */ new WeakMap();
14
+ var inputPolicy = /* @__PURE__ */ __name((input) => policies.get(input) ?? {}, "inputPolicy");
15
+ var provideInputPolicy = /* @__PURE__ */ __name((input, policy) => {
16
+ const previous = policies.get(input);
17
+ policies.set(input, policy);
18
+ return () => {
19
+ if (previous)
20
+ policies.set(input, previous);
21
+ else
22
+ policies.delete(input);
23
+ };
24
+ }, "provideInputPolicy");
25
+ var bufferedInput = /* @__PURE__ */ __name((input, options = {}) => {
26
+ const policy = inputPolicy(input);
27
+ const maxBytes = options.maxBytes ?? policy.maxBytes ?? MAX_BUFFERED_INPUT;
28
+ const signals = [options.signal, policy.signal].filter((one) => one !== void 0);
29
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
30
+ const state = input;
31
+ if (state.readableEnded)
32
+ return Promise.resolve(Buffer.alloc(0));
33
+ if (state.destroyed)
34
+ return Promise.reject(new CliError("validation_error", "input closed before EOF", { reason: "input.closed" }));
35
+ return new Promise((resolve, reject) => {
36
+ const chunks = [];
37
+ let bytes = 0;
38
+ const cleanup = /* @__PURE__ */ __name(() => {
39
+ input.off("data", data).off("end", end).off("error", error).off("close", closed);
40
+ signal?.removeEventListener("abort", aborted);
41
+ input.pause();
42
+ }, "cleanup");
43
+ const error = /* @__PURE__ */ __name((cause) => {
44
+ cleanup();
45
+ reject(cause);
46
+ }, "error");
47
+ const aborted = /* @__PURE__ */ __name(() => error(new CliError("cancelled", "input cancelled", { retryable: false })), "aborted");
48
+ const closed = /* @__PURE__ */ __name(() => error(new CliError("validation_error", "input closed before EOF", { reason: "input.closed" })), "closed");
49
+ const end = /* @__PURE__ */ __name(() => {
50
+ cleanup();
51
+ resolve(Buffer.concat(chunks, bytes));
52
+ }, "end");
53
+ const data = /* @__PURE__ */ __name((chunk) => {
54
+ const buffer = Buffer.from(chunk);
55
+ bytes += buffer.length;
56
+ if (bytes > maxBytes) {
57
+ error(new CliError("validation_error", `buffered input exceeds ${maxBytes} bytes \u2014 use a smaller input or --max-input-bytes`, {
58
+ reason: "input.too-large",
59
+ max_bytes: maxBytes,
60
+ retryable: false
61
+ }));
62
+ return;
63
+ }
64
+ chunks.push(buffer);
65
+ }, "data");
66
+ if (signal?.aborted) {
67
+ aborted();
68
+ return;
69
+ }
70
+ input.on("data", data).once("end", end).once("error", error).once("close", closed);
71
+ signal?.addEventListener("abort", aborted, { once: true });
72
+ input.resume();
73
+ });
74
+ }, "bufferedInput");
75
+
76
+ export {
77
+ MAX_BUFFERED_INPUT,
78
+ MAX_SECRET_INPUT,
79
+ inputPolicy,
80
+ provideInputPolicy,
81
+ bufferedInput
82
+ };
@@ -0,0 +1,35 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ __name
5
+ } from "./chunk-AFV74GK3.js";
6
+
7
+ // tg-bundle:from:tg-bundle:from
8
+ import * as module from "node:module";
9
+ import { dirname } from "node:path";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ var resolveFrom = /* @__PURE__ */ __name((parent, specifier) => {
12
+ if (globalThis.Bun) {
13
+ if (specifier.includes(":")) return import.meta.resolve(specifier);
14
+ try {
15
+ return pathToFileURL(globalThis.Bun.resolveSync(specifier, dirname(fileURLToPath(parent)))).href;
16
+ } catch {
17
+ return import.meta.resolve(specifier);
18
+ }
19
+ }
20
+ if (!module.registerHooks) return import.meta.resolve(specifier);
21
+ const hooks = module.registerHooks({
22
+ resolve: /* @__PURE__ */ __name((asked, context, next) => next(asked, asked === specifier ? { ...context, parentURL: parent } : context), "resolve")
23
+ });
24
+ try {
25
+ return import.meta.resolve(specifier);
26
+ } finally {
27
+ hooks.deregister();
28
+ }
29
+ }, "resolveFrom");
30
+ var importFrom = /* @__PURE__ */ __name(async (parent, specifier) => import(resolveFrom(parent, specifier)), "importFrom");
31
+
32
+ export {
33
+ resolveFrom,
34
+ importFrom
35
+ };
@@ -0,0 +1,285 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ OAuthError,
5
+ OAuthErrorCode
6
+ } from "./chunk-3KHKYYCR.js";
7
+ import {
8
+ ACCESS_SECONDS,
9
+ REFRESH_SECONDS,
10
+ readStored
11
+ } from "./chunk-Z2FHEIXN.js";
12
+ import {
13
+ __name
14
+ } from "./chunk-AFV74GK3.js";
15
+
16
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/mcp/http/oauth.js
17
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
18
+ import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
19
+ import { dirname } from "node:path";
20
+ var AUTH_CODE_MS = 60 * 1e3;
21
+ var LOGIN_CODE_MS = 10 * 60 * 1e3;
22
+ var WRONG_TRIES = 5;
23
+ var WRONG_CODE_WAIT_MS = 3e4;
24
+ var MAX_CLIENTS = 10;
25
+ var CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
26
+ var hash = /* @__PURE__ */ __name((value) => createHash("sha256").update(value).digest("base64url"), "hash");
27
+ var secret = /* @__PURE__ */ __name(() => randomBytes(32).toString("base64url"), "secret");
28
+ var same = /* @__PURE__ */ __name((given, expected) => {
29
+ const left = Buffer.from(given);
30
+ const right = Buffer.from(expected);
31
+ return left.byteLength === right.byteLength && timingSafeEqual(left, right);
32
+ }, "same");
33
+ var tokenFile = /* @__PURE__ */ __name((path) => ({
34
+ read: /* @__PURE__ */ __name(() => readStored(path), "read"),
35
+ write: /* @__PURE__ */ __name((stored) => {
36
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
37
+ const temporary = `${path}.${randomBytes(16).toString("hex")}.tmp`;
38
+ writeFileSync(temporary, JSON.stringify(stored), { mode: 384, flag: "wx" });
39
+ chmodSync(temporary, 384);
40
+ renameSync(temporary, path);
41
+ }, "write")
42
+ }), "tokenFile");
43
+ var revokeAll = /* @__PURE__ */ __name((path) => rmSync(path, { force: true }), "revokeAll");
44
+ var json = /* @__PURE__ */ __name((body, status = 200) => new Response(JSON.stringify(body), {
45
+ status,
46
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
47
+ }), "json");
48
+ var oauthError = /* @__PURE__ */ __name((error, description, status = 400) => json({ error, error_description: description }, status), "oauthError");
49
+ var escapeHtml = /* @__PURE__ */ __name((value) => value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`), "escapeHtml");
50
+ var redirectAllowed = /* @__PURE__ */ __name((uri) => {
51
+ try {
52
+ const url = new URL(uri);
53
+ if (url.hash)
54
+ return false;
55
+ return url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname);
56
+ } catch {
57
+ return false;
58
+ }
59
+ }, "redirectAllowed");
60
+ var ownerLogin = /* @__PURE__ */ __name(({ issuer, resource, file, appName, onCode, now = /* @__PURE__ */ __name(() => Date.now(), "now") }) => {
61
+ const store = tokenFile(file);
62
+ const codes = /* @__PURE__ */ new Map();
63
+ let login = { value: "", expires: 0 };
64
+ let wrong = 0;
65
+ let retryAt = 0;
66
+ let renewal;
67
+ const freshCode = /* @__PURE__ */ __name(() => {
68
+ const part = /* @__PURE__ */ __name(() => Array.from({ length: 4 }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join(""), "part");
69
+ login = { value: `${part()}-${part()}`, expires: now() + LOGIN_CODE_MS };
70
+ clearTimeout(renewal);
71
+ renewal = setTimeout(freshCode, LOGIN_CODE_MS);
72
+ renewal.unref();
73
+ onCode(login.value, new Date(login.expires));
74
+ }, "freshCode");
75
+ freshCode();
76
+ const base = issuer.pathname.replace(/\/+$/, "");
77
+ const endpoint = /* @__PURE__ */ __name((path) => new URL(`${base}${path}`, issuer.origin).href, "endpoint");
78
+ const metadata = {
79
+ issuer: issuer.href,
80
+ authorization_endpoint: endpoint("/authorize"),
81
+ token_endpoint: endpoint("/token"),
82
+ registration_endpoint: endpoint("/register"),
83
+ response_types_supported: ["code"],
84
+ grant_types_supported: ["authorization_code", "refresh_token"],
85
+ code_challenge_methods_supported: ["S256"],
86
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"]
87
+ };
88
+ const issue = /* @__PURE__ */ __name((stored, clientId) => {
89
+ const access = secret();
90
+ const refresh = secret();
91
+ const seconds = Math.floor(now() / 1e3);
92
+ stored.tokens = stored.tokens.filter((one) => one.expiresAt > seconds);
93
+ stored.tokens.push({ hash: hash(access), kind: "access", clientId, expiresAt: seconds + ACCESS_SECONDS }, { hash: hash(refresh), kind: "refresh", clientId, expiresAt: seconds + REFRESH_SECONDS });
94
+ store.write(stored);
95
+ return json({ access_token: access, token_type: "Bearer", expires_in: ACCESS_SECONDS, refresh_token: refresh });
96
+ }, "issue");
97
+ const clientOf = /* @__PURE__ */ __name((stored, request, form) => {
98
+ let id = form.get("client_id") ?? "";
99
+ let given = form.get("client_secret") ?? void 0;
100
+ const basic = request.headers.get("authorization");
101
+ if (basic?.startsWith("Basic ")) {
102
+ const [user = "", password = ""] = Buffer.from(basic.slice(6), "base64").toString().split(":");
103
+ id = decodeURIComponent(user);
104
+ given = decodeURIComponent(password);
105
+ }
106
+ const client = stored.clients.find((one) => one.id === id);
107
+ if (!client)
108
+ return void 0;
109
+ if (client.authMethod === "none")
110
+ return client;
111
+ return given !== void 0 && client.secretHash && same(hash(given), client.secretHash) ? client : void 0;
112
+ }, "clientOf");
113
+ const register = /* @__PURE__ */ __name(async (request) => {
114
+ const body = await request.json().catch(() => null);
115
+ const uris = Array.isArray(body?.redirect_uris) ? body.redirect_uris.filter((one) => typeof one === "string") : [];
116
+ if (uris.length === 0 || !uris.every(redirectAllowed))
117
+ return oauthError("invalid_redirect_uri", "redirect_uris must be https URLs");
118
+ const requested = body?.token_endpoint_auth_method;
119
+ const authMethod = requested === "client_secret_post" || requested === "client_secret_basic" ? requested : "none";
120
+ const clientSecret = authMethod === "none" ? void 0 : secret();
121
+ const name = typeof body?.client_name === "string" ? body.client_name.slice(0, 100) : void 0;
122
+ const client = {
123
+ id: secret(),
124
+ redirectUris: uris,
125
+ authMethod,
126
+ issuedAt: Math.floor(now() / 1e3),
127
+ ...name ? { name } : {},
128
+ ...clientSecret ? { secretHash: hash(clientSecret) } : {}
129
+ };
130
+ const stored = store.read();
131
+ const seconds = Math.floor(now() / 1e3);
132
+ const holding = new Set(stored.tokens.filter((one) => one.expiresAt > seconds).map((one) => one.clientId));
133
+ stored.clients.push(client);
134
+ while (stored.clients.length > MAX_CLIENTS) {
135
+ const idle = stored.clients.findIndex((one) => !holding.has(one.id));
136
+ if (idle === -1)
137
+ return oauthError("invalid_client_metadata", "too many logged-in apps \u2014 run mcp --revoke first");
138
+ stored.clients.splice(idle, 1);
139
+ }
140
+ store.write(stored);
141
+ return json({
142
+ client_id: client.id,
143
+ client_id_issued_at: client.issuedAt,
144
+ redirect_uris: uris,
145
+ token_endpoint_auth_method: authMethod,
146
+ grant_types: ["authorization_code", "refresh_token"],
147
+ response_types: ["code"],
148
+ ...name ? { client_name: name } : {},
149
+ ...clientSecret ? { client_secret: clientSecret, client_secret_expires_at: 0 } : {}
150
+ }, 201);
151
+ }, "register");
152
+ const page = /* @__PURE__ */ __name((params, client, message) => {
153
+ const hidden = ["response_type", "client_id", "redirect_uri", "code_challenge", "code_challenge_method", "state"].map((name) => `<input type="hidden" name="${name}" value="${escapeHtml(params.get(name) ?? "")}">`).join("");
154
+ const who = escapeHtml(client.name ?? "an application");
155
+ const target = new URL(params.get("redirect_uri") ?? "");
156
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(appName)} login</title><style>body{font:16px system-ui,sans-serif;max-width:28rem;margin:3rem auto;padding:0 1rem;color:#1d2430}input[type=text]{font:20px ui-monospace,monospace;letter-spacing:.1em;width:100%;padding:.5rem;margin:.5rem 0 1rem;box-sizing:border-box}button{font:inherit;padding:.5rem 1rem}.error{color:#b42318}</style></head><body><h1>${escapeHtml(appName)}</h1><p>An app that calls itself <strong>${who}</strong> asks to reach your messages through <code>${escapeHtml(appName)} mcp --http</code>.</p><p>After you allow it, the login goes to <strong>${escapeHtml(target.host)}</strong>. Allow only if that is the app you are connecting, such as chatgpt.com or claude.ai.</p><p>Type the code shown in WireCat Desktop, or in the terminal where the server runs. If you did not start this login, close this page.</p>${message ? `<p class="error">${escapeHtml(message)}</p>` : ""}<form method="post" action="${escapeHtml(`${base}/authorize`)}">${hidden}<label>Login code<input type="text" name="login_code" autocomplete="off" autofocus required></label><button type="submit">Allow</button></form></body></html>`;
157
+ return new Response(html, {
158
+ status: message ? 400 : 200,
159
+ headers: {
160
+ "content-type": "text/html; charset=utf-8",
161
+ "cache-control": "no-store",
162
+ "x-frame-options": "DENY",
163
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${target.origin}; frame-ancestors 'none'`,
164
+ // no-referrer makes the browser post this form with `Origin: null`, which the Origin check refuses.
165
+ "referrer-policy": "same-origin"
166
+ }
167
+ });
168
+ }, "page");
169
+ const authorize = /* @__PURE__ */ __name(async (request) => {
170
+ const params = request.method === "POST" ? new URLSearchParams(await request.text()) : new URL(request.url).searchParams;
171
+ const stored = store.read();
172
+ const client = stored.clients.find((one) => one.id === params.get("client_id"));
173
+ const redirectUri = params.get("redirect_uri") ?? "";
174
+ if (!client?.redirectUris.includes(redirectUri))
175
+ return new Response("Unknown client or redirect address.", { status: 400 });
176
+ if (params.get("response_type") !== "code" || params.get("code_challenge_method") !== "S256" || !params.get("code_challenge"))
177
+ return new Response("This server needs response_type=code and PKCE with S256.", { status: 400 });
178
+ if (request.method !== "POST")
179
+ return page(params, client);
180
+ const throttled = /* @__PURE__ */ __name(() => new Response("Too many wrong codes. Wait, then try the new code.", {
181
+ status: 429,
182
+ headers: { "retry-after": String(Math.ceil((retryAt - now()) / 1e3)) }
183
+ }), "throttled");
184
+ if (wrong >= WRONG_TRIES) {
185
+ if (now() < retryAt)
186
+ return throttled();
187
+ wrong = 0;
188
+ freshCode();
189
+ }
190
+ const typed = (params.get("login_code") ?? "").trim().toUpperCase();
191
+ if (login.expires < now()) {
192
+ freshCode();
193
+ return page(params, client, "The code expired. A new one is shown in WireCat Desktop and in the terminal.");
194
+ }
195
+ if (!same(typed, login.value)) {
196
+ wrong += 1;
197
+ if (wrong >= WRONG_TRIES) {
198
+ retryAt = now() + WRONG_CODE_WAIT_MS;
199
+ return throttled();
200
+ }
201
+ return page(params, client, `Wrong code. ${WRONG_TRIES - wrong} tries left.`);
202
+ }
203
+ wrong = 0;
204
+ freshCode();
205
+ const code = secret();
206
+ codes.set(hash(code), {
207
+ clientId: client.id,
208
+ redirectUri,
209
+ challenge: params.get("code_challenge") ?? "",
210
+ expires: now() + AUTH_CODE_MS
211
+ });
212
+ const target = new URL(redirectUri);
213
+ target.searchParams.set("code", code);
214
+ const state = params.get("state");
215
+ if (state)
216
+ target.searchParams.set("state", state);
217
+ target.searchParams.set("iss", issuer.href);
218
+ return new Response(null, { status: 302, headers: { location: target.href, "cache-control": "no-store" } });
219
+ }, "authorize");
220
+ const token = /* @__PURE__ */ __name(async (request) => {
221
+ const form = new URLSearchParams(await request.text());
222
+ const stored = store.read();
223
+ const client = clientOf(stored, request, form);
224
+ if (!client)
225
+ return oauthError("invalid_client", "unknown client or wrong secret", 401);
226
+ const requestedResource = form.get("resource");
227
+ if (requestedResource && requestedResource !== resource.href)
228
+ return oauthError("invalid_target", "this server issues tokens only for its own MCP endpoint");
229
+ if (form.get("grant_type") === "authorization_code") {
230
+ const key = hash(form.get("code") ?? "");
231
+ const entry = codes.get(key);
232
+ codes.delete(key);
233
+ const verifier2 = form.get("code_verifier") ?? "";
234
+ const challenge = createHash("sha256").update(verifier2).digest("base64url");
235
+ if (!entry || entry.expires < now() || entry.clientId !== client.id || entry.redirectUri !== form.get("redirect_uri") || !same(challenge, entry.challenge))
236
+ return oauthError("invalid_grant", "the code is wrong, used or expired");
237
+ return issue(stored, client.id);
238
+ }
239
+ if (form.get("grant_type") === "refresh_token") {
240
+ const key = hash(form.get("refresh_token") ?? "");
241
+ const seconds = Math.floor(now() / 1e3);
242
+ const found = stored.tokens.find((one) => one.kind === "refresh" && one.hash === key);
243
+ if (!found || found.clientId !== client.id || found.expiresAt <= seconds)
244
+ return oauthError("invalid_grant", "the refresh token is wrong, used or expired");
245
+ stored.tokens = stored.tokens.filter((one) => one !== found);
246
+ return issue(stored, client.id);
247
+ }
248
+ return oauthError("unsupported_grant_type", "use authorization_code or refresh_token");
249
+ }, "token");
250
+ const verifier = {
251
+ verifyAccessToken: /* @__PURE__ */ __name(async (presented) => {
252
+ const seconds = Math.floor(now() / 1e3);
253
+ const found = store.read().tokens.find((one) => one.kind === "access" && one.hash === hash(presented));
254
+ if (!found || found.expiresAt <= seconds)
255
+ throw new OAuthError(OAuthErrorCode.InvalidToken, "the token is unknown or expired");
256
+ return {
257
+ token: presented,
258
+ clientId: found.clientId,
259
+ scopes: [],
260
+ expiresAt: found.expiresAt,
261
+ resource
262
+ };
263
+ }, "verifyAccessToken")
264
+ };
265
+ return {
266
+ code: /* @__PURE__ */ __name(() => login.value, "code"),
267
+ close: /* @__PURE__ */ __name(() => clearTimeout(renewal), "close"),
268
+ metadata,
269
+ verifier,
270
+ handle: /* @__PURE__ */ __name(async (request, path = new URL(request.url).pathname) => {
271
+ if (path === `${base}/register` && request.method === "POST")
272
+ return register(request);
273
+ if (path === `${base}/authorize` && (request.method === "GET" || request.method === "POST"))
274
+ return authorize(request);
275
+ if (path === `${base}/token` && request.method === "POST")
276
+ return token(request);
277
+ return void 0;
278
+ }, "handle")
279
+ };
280
+ }, "ownerLogin");
281
+
282
+ export {
283
+ revokeAll,
284
+ ownerLogin
285
+ };
@@ -0,0 +1,71 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ proxyError,
5
+ proxyLabel
6
+ } from "./chunk-2IM4M7Q2.js";
7
+ import {
8
+ CliError
9
+ } from "./chunk-WE3LBRMB.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-AFV74GK3.js";
13
+
14
+ // dist/telegram/proxy-transport.js
15
+ import { HttpProxyConnectionError, HttpProxyTcpTransport, MtProxyTcpTransport, SocksProxyConnectionError, SocksProxyTcpTransport } from "@mtcute/node";
16
+ var transportOf = /* @__PURE__ */ __name((proxy) => {
17
+ const auth = {
18
+ ...proxy.user === void 0 ? {} : { user: proxy.user },
19
+ ...proxy.secret === void 0 ? {} : { password: proxy.secret }
20
+ };
21
+ switch (proxy.kind) {
22
+ case "socks5":
23
+ return new SocksProxyTcpTransport({ version: 5, host: proxy.host, port: proxy.port, ...auth });
24
+ case "http":
25
+ return new HttpProxyTcpTransport({ host: proxy.host, port: proxy.port, tls: proxy.tls, ...auth });
26
+ case "mtproxy":
27
+ try {
28
+ return new MtProxyTcpTransport({ host: proxy.host, port: proxy.port, secret: proxy.secret ?? "" });
29
+ } catch {
30
+ throw new CliError("configuration_error", `the MTProxy ${proxyLabel(proxy)} has a secret tg cannot read`);
31
+ }
32
+ }
33
+ }, "transportOf");
34
+ var checkProxy = /* @__PURE__ */ __name((proxy) => {
35
+ transportOf(proxy);
36
+ }, "checkProxy");
37
+ var proxyFailure = /* @__PURE__ */ __name((proxy, error) => {
38
+ const code = error?.code;
39
+ return proxyError(proxy, error instanceof SocksProxyConnectionError || error instanceof HttpProxyConnectionError ? `refused: ${hidden(error.message.replace(/^Error while connecting to [^:]+:\d+: /, ""), proxy)}` : typeof code === "string" ? `cannot be reached (${code})` : "did not let tg through");
40
+ }, "proxyFailure");
41
+ var hidden = /* @__PURE__ */ __name((text, proxy) => proxy.secret ? text.split(proxy.secret).join("[redacted]") : text, "hidden");
42
+ var proxiedTransport = /* @__PURE__ */ __name((proxy) => {
43
+ const transport = transportOf(proxy);
44
+ const connect = transport.connect.bind(transport);
45
+ let worked = false;
46
+ let fail = /* @__PURE__ */ __name(() => {
47
+ }, "fail");
48
+ const failed = new Promise((_, reject) => {
49
+ fail = reject;
50
+ });
51
+ failed.catch(() => {
52
+ });
53
+ transport.connect = async (dc, signal) => {
54
+ try {
55
+ const connection = await connect(dc, signal);
56
+ worked = true;
57
+ return connection;
58
+ } catch (error) {
59
+ if (!worked && !signal.aborted)
60
+ fail(proxyFailure(proxy, error));
61
+ throw error;
62
+ }
63
+ };
64
+ return { transport, failed };
65
+ }, "proxiedTransport");
66
+
67
+ export {
68
+ checkProxy,
69
+ proxyFailure,
70
+ proxiedTransport
71
+ };