@pmndre/pine 0.0.0-stage → 0.22.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/LICENSE +21 -0
- package/README.md +226 -2
- package/bin/pine.js +27 -0
- package/docs/SKILL.md +234 -0
- package/docs/references/agents.md +454 -0
- package/docs/references/coding.md +311 -0
- package/docs/references/computer.md +212 -0
- package/docs/references/configuration.md +310 -0
- package/docs/references/events.md +267 -0
- package/docs/references/mcp.md +420 -0
- package/docs/references/operations.md +394 -0
- package/docs/references/overview.md +195 -0
- package/docs/references/security.md +896 -0
- package/docs/references/setup.md +385 -0
- package/docs/references/sources.md +772 -0
- package/docs/references/stack.md +121 -0
- package/docs/references/tui.md +575 -0
- package/examples/home/.env.example +7 -0
- package/examples/home/USER.md +4 -0
- package/examples/home/agents/main/agent.json +4 -0
- package/examples/home/agents/main/workspace/AGENTS.md +14 -0
- package/examples/home/agents/main/workspace/MEMORY.md +4 -0
- package/examples/home/agents/main/workspace/SOUL.md +4 -0
- package/examples/home/models.json +62 -0
- package/examples/home/pine.json +34 -0
- package/examples/home/skills/README.txt +7 -0
- package/examples/launchd/com.pine.daemon.plist +32 -0
- package/examples/systemd/pine.service +22 -0
- package/mcp/browser.d.ts +99 -0
- package/mcp/browser.js +496 -0
- package/mcp/commands.d.ts +20 -0
- package/mcp/commands.js +88 -0
- package/mcp/computer.d.ts +139 -0
- package/mcp/computer.js +698 -0
- package/mcp/computer.swift +989 -0
- package/mcp/lib.d.ts +23 -0
- package/mcp/lib.js +52 -0
- package/mcp/web.d.ts +6 -0
- package/mcp/web.js +140 -0
- package/package.json +32 -4
- package/src/access.d.ts +112 -0
- package/src/access.js +438 -0
- package/src/actions.d.ts +75 -0
- package/src/actions.js +167 -0
- package/src/admin.d.ts +167 -0
- package/src/admin.js +625 -0
- package/src/agent-admin.d.ts +24 -0
- package/src/agent-admin.js +55 -0
- package/src/agents.d.ts +540 -0
- package/src/agents.js +2776 -0
- package/src/background.d.ts +29 -0
- package/src/background.js +100 -0
- package/src/cli.d.ts +2 -0
- package/src/cli.js +777 -0
- package/src/computer.d.ts +30 -0
- package/src/computer.js +32 -0
- package/src/config.d.ts +396 -0
- package/src/config.js +549 -0
- package/src/dev/claude-model.d.ts +37 -0
- package/src/dev/claude-model.js +204 -0
- package/src/env-file.d.ts +4 -0
- package/src/env-file.js +40 -0
- package/src/goals.d.ts +133 -0
- package/src/goals.js +316 -0
- package/src/http.d.ts +46 -0
- package/src/http.js +509 -0
- package/src/limiter.d.ts +32 -0
- package/src/limiter.js +84 -0
- package/src/login.d.ts +23 -0
- package/src/login.js +130 -0
- package/src/manual.d.ts +61 -0
- package/src/manual.js +443 -0
- package/src/mcp-config.d.ts +49 -0
- package/src/mcp-config.js +182 -0
- package/src/models.d.ts +90 -0
- package/src/models.js +274 -0
- package/src/net.d.ts +50 -0
- package/src/net.js +150 -0
- package/src/pine.d.ts +32 -0
- package/src/pine.js +134 -0
- package/src/programs.d.ts +123 -0
- package/src/programs.js +412 -0
- package/src/router.d.ts +56 -0
- package/src/router.js +164 -0
- package/src/sandbox-fs.d.ts +34 -0
- package/src/sandbox-fs.js +186 -0
- package/src/sandbox-linux.d.ts +96 -0
- package/src/sandbox-linux.js +297 -0
- package/src/sandbox-setup.d.ts +70 -0
- package/src/sandbox-setup.js +216 -0
- package/src/security.d.ts +238 -0
- package/src/security.js +660 -0
- package/src/skills.d.ts +67 -0
- package/src/skills.js +163 -0
- package/src/snapshots.d.ts +68 -0
- package/src/snapshots.js +306 -0
- package/src/source-types.d.ts +61 -0
- package/src/source-types.js +1 -0
- package/src/sources/command.d.ts +4 -0
- package/src/sources/command.js +77 -0
- package/src/sources/folder.d.ts +6 -0
- package/src/sources/folder.js +116 -0
- package/src/sources/ftp.d.ts +4 -0
- package/src/sources/ftp.js +307 -0
- package/src/sources/http.d.ts +4 -0
- package/src/sources/http.js +201 -0
- package/src/sources/mqtt.d.ts +18 -0
- package/src/sources/mqtt.js +97 -0
- package/src/sources/telegram.d.ts +22 -0
- package/src/sources/telegram.js +283 -0
- package/src/sources/webhook.d.ts +4 -0
- package/src/sources/webhook.js +52 -0
- package/src/sources.d.ts +344 -0
- package/src/sources.js +966 -0
- package/src/store.d.ts +99 -0
- package/src/store.js +277 -0
- package/src/timers.d.ts +83 -0
- package/src/timers.js +318 -0
- package/src/tools.d.ts +11 -0
- package/src/tools.js +1297 -0
- package/src/tui/app.d.ts +305 -0
- package/src/tui/app.js +3195 -0
- package/src/tui/client.d.ts +236 -0
- package/src/tui/client.js +131 -0
- package/src/tui/code-pane.d.ts +68 -0
- package/src/tui/code-pane.js +535 -0
- package/src/tui/highlight.d.ts +8 -0
- package/src/tui/highlight.js +86 -0
- package/src/tui/picture.d.ts +206 -0
- package/src/tui/picture.js +801 -0
- package/src/tui/run.d.ts +8 -0
- package/src/tui/run.js +97 -0
- package/src/tui/theme.d.ts +32 -0
- package/src/tui/theme.js +128 -0
- package/src/tui/undo.d.ts +5 -0
- package/src/tui/undo.js +50 -0
- package/src/tui/voice.d.ts +49 -0
- package/src/tui/voice.js +155 -0
- package/src/tui/voice.swift +223 -0
- package/src/types.d.ts +139 -0
- package/src/types.js +1 -0
- package/src/undo.d.ts +224 -0
- package/src/undo.js +465 -0
- package/src/update.d.ts +35 -0
- package/src/update.js +130 -0
- package/src/util.d.ts +65 -0
- package/src/util.js +171 -0
- package/src/watching.d.ts +20 -0
- package/src/watching.js +68 -0
- package/src/workspace-view.d.ts +72 -0
- package/src/workspace-view.js +221 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { fetch } from "undici";
|
|
4
|
+
import { isLocalName, isPrivateAddress, publicOnlyAgent } from "../net.js";
|
|
5
|
+
import { errText, getPath, parseDuration } from "../util.js";
|
|
6
|
+
import { clip, found, harmless, lineDiff, pageText, pattern, shown } from "../watching.js";
|
|
7
|
+
/**
|
|
8
|
+
* A web address, looked at again and again: reports when what it answers changes, and when it
|
|
9
|
+
* stops or starts answering. For pages and services that cannot call you: a price, a version, a
|
|
10
|
+
* status page, a device with a state page on your network.
|
|
11
|
+
*
|
|
12
|
+
* options: { url, every?, path?, match?, headers?, token?, tokenHeader?, local? }
|
|
13
|
+
* every how often to look ("5m" by default)
|
|
14
|
+
* path for a JSON answer: watch only this field ("data.price")
|
|
15
|
+
* match for a page or text: watch only what this regular expression finds
|
|
16
|
+
* headers headers to send
|
|
17
|
+
* token sent as "Authorization: Bearer <token>", or as it is in the header `tokenHeader`
|
|
18
|
+
* local the address is on the owner's own network, under a name that does not say so
|
|
19
|
+
*
|
|
20
|
+
* event "changed": { url, value, previous } with path or match
|
|
21
|
+
* { url, added, removed, more? } without: the lines that are new and gone
|
|
22
|
+
* event "down": { url, error, looks } after three failed looks in a row
|
|
23
|
+
* event "up": { url } when it answers again
|
|
24
|
+
*
|
|
25
|
+
* The first look is the starting point and reports nothing.
|
|
26
|
+
*/
|
|
27
|
+
const MIN = 30_000;
|
|
28
|
+
const DOWN_AFTER = 3;
|
|
29
|
+
const MAX_BODY = 1024 * 1024;
|
|
30
|
+
const TIMEOUT = 20_000;
|
|
31
|
+
/**
|
|
32
|
+
* Whether an address says by itself that it is on this computer or the local network. Such an
|
|
33
|
+
* address the owner confirmed as what it is. Any other one must stay on the public internet: a
|
|
34
|
+
* name that one day points into the local network is not followed there.
|
|
35
|
+
*/
|
|
36
|
+
const isLocal = (url) => {
|
|
37
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
38
|
+
return isLocalName(host) || (net.isIP(host) !== 0 && isPrivateAddress(host));
|
|
39
|
+
};
|
|
40
|
+
/** Why a look failed, in words: what lies behind "fetch failed". */
|
|
41
|
+
const reason = (e, url) => {
|
|
42
|
+
const text = errText(e?.cause ?? e);
|
|
43
|
+
return /resolves to a private address/.test(text) ? `${url.hostname} leads to an address on your own network. If that is meant, set the source up again with "local": true` : text;
|
|
44
|
+
};
|
|
45
|
+
/** Headers that carry a secret. Those go into `token`, which is kept out of the configuration. */
|
|
46
|
+
const SECRET_HEADERS = ["authorization", "proxy-authorization", "cookie"];
|
|
47
|
+
export const type = {
|
|
48
|
+
summary: "a web address looked at again and again: reports when what it answers changes (the whole page, or one value in it: a price, a version, a state), and when it stops or starts answering. For pages and services that cannot call you",
|
|
49
|
+
options: Type.Object({
|
|
50
|
+
url: Type.String({ description: "the address to look at, https://... (http:// for a device on the local network)" }),
|
|
51
|
+
every: Type.Optional(Type.String({ description: 'how often to look, e.g. "5m", "1h". Default "5m", at least "30s"' })),
|
|
52
|
+
path: Type.Optional(Type.String({ description: 'for an answer in JSON: watch only this field, e.g. "data.price" or "items.0.state"' })),
|
|
53
|
+
match: Type.Optional(Type.String({ description: 'for a page or text: watch only what this regular expression finds (its first group, if it has one), e.g. "Price: ([0-9.,]+)". Without path or match the whole text counts, and a page that shows the time or a counter changes at every look' })),
|
|
54
|
+
headers: Type.Optional(Type.Record(Type.String(), Type.String(), { description: 'headers to send, e.g. {"accept": "application/json"}. Not for secrets' })),
|
|
55
|
+
token: Type.Optional(Type.String({ description: "an access token or key, if the address wants one. Sent as Authorization: Bearer <token>", secret: true })),
|
|
56
|
+
tokenHeader: Type.Optional(Type.String({ description: 'send the token as this header instead, as it is, e.g. "x-api-key"' })),
|
|
57
|
+
local: Type.Optional(Type.Boolean({ description: "true if the address is on your owner's own network under a name that does not say so (nas.home, ha.lan). Not needed for an IP address, localhost or a .local name" })),
|
|
58
|
+
}, { additionalProperties: false }),
|
|
59
|
+
plan(o) {
|
|
60
|
+
let url;
|
|
61
|
+
try {
|
|
62
|
+
url = new URL(o.url);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new Error(`"${o.url}" is not an address. It looks like https://example.com/page`);
|
|
66
|
+
}
|
|
67
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
68
|
+
throw new Error("the address must start with https:// or http://");
|
|
69
|
+
if (url.username || url.password)
|
|
70
|
+
throw new Error('an address with a user name or password in it is not taken: leave it out of the address and name "token" in "ask"');
|
|
71
|
+
const every = o.every ?? "5m";
|
|
72
|
+
if (parseDuration(every) < MIN)
|
|
73
|
+
throw new Error('"every" must be at least "30s"');
|
|
74
|
+
if (o.path && o.match)
|
|
75
|
+
throw new Error('"path" is for an answer in JSON, "match" for a page or text: give one of them');
|
|
76
|
+
if (o.match)
|
|
77
|
+
pattern(o.match);
|
|
78
|
+
const secret = Object.keys(o.headers ?? {}).filter((h) => SECRET_HEADERS.includes(h.toLowerCase()));
|
|
79
|
+
if (secret.length)
|
|
80
|
+
throw new Error(`the header ${secret.join(", ")} carries a secret: leave it out, name "token" in "ask" and give "tokenHeader": "${secret[0].toLowerCase()}"`);
|
|
81
|
+
if (o.tokenHeader && !/^[A-Za-z0-9-]+$/.test(o.tokenHeader))
|
|
82
|
+
throw new Error('"tokenHeader" is the name of a header, e.g. "x-api-key"');
|
|
83
|
+
const what = o.path ? `the field ${o.path} of what it answers` : o.match ? `what /${o.match}/ finds in it` : "what it answers";
|
|
84
|
+
return {
|
|
85
|
+
options: { ...o, url: url.href },
|
|
86
|
+
does: [`ask ${clip(url.href, 160)}${o.local || isLocal(url) ? " (an address on your own network or this computer)" : ""} every ${every} and report when ${what} changes, and when it stops or starts answering`, ...(o.token ? [`with the token given, sent only to ${url.host}`] : [])],
|
|
87
|
+
opens: true,
|
|
88
|
+
tell: "Its first look is the starting point and reports nothing; from then on only a change does. The sources tool shows what it found at the last look.",
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
/** One look: the answer's text, at most 1 MB of it. A redirect is followed only on the same host. */
|
|
93
|
+
async function get(start, o, guard, signal) {
|
|
94
|
+
const headers = { ...(o.headers ?? {}) };
|
|
95
|
+
if (o.token)
|
|
96
|
+
headers[o.tokenHeader ?? "authorization"] = o.tokenHeader ? o.token : `Bearer ${o.token}`;
|
|
97
|
+
let at = start;
|
|
98
|
+
for (let hop = 0; hop < 6; hop++) {
|
|
99
|
+
const res = await fetch(at, { headers, redirect: "manual", signal: AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT)]), ...(guard ? { dispatcher: guard } : {}) });
|
|
100
|
+
const to = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
|
|
101
|
+
if (to) {
|
|
102
|
+
await res.body?.cancel().catch(() => { });
|
|
103
|
+
const next = new URL(to, at);
|
|
104
|
+
// The owner confirmed one host. Another one is another decision, and must not get the token.
|
|
105
|
+
const upgrade = at.protocol === "http:" && next.protocol === "https:";
|
|
106
|
+
if (next.hostname !== start.hostname || (next.protocol !== at.protocol && !upgrade) || (next.port !== at.port && !upgrade))
|
|
107
|
+
throw new Error(`it sends on to ${next.host}, which is not the address that was confirmed. If that is the right one, set the source up with it`);
|
|
108
|
+
at = next;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (!res.ok) {
|
|
112
|
+
await res.body?.cancel().catch(() => { });
|
|
113
|
+
throw new Error(`it answered ${res.status}`);
|
|
114
|
+
}
|
|
115
|
+
const chunks = [];
|
|
116
|
+
let size = 0;
|
|
117
|
+
const reader = res.body?.getReader();
|
|
118
|
+
while (reader) {
|
|
119
|
+
const { done, value } = await reader.read();
|
|
120
|
+
if (done)
|
|
121
|
+
break;
|
|
122
|
+
chunks.push(Buffer.from(value.subarray(0, MAX_BODY - size)));
|
|
123
|
+
size += value.length;
|
|
124
|
+
if (size >= MAX_BODY) {
|
|
125
|
+
await reader.cancel().catch(() => { });
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { type: res.headers.get("content-type") ?? "", body: Buffer.concat(chunks).toString("utf8") };
|
|
130
|
+
}
|
|
131
|
+
throw new Error("it sends on and on (more than five redirects)");
|
|
132
|
+
}
|
|
133
|
+
export default function http(source) {
|
|
134
|
+
const o = source.options;
|
|
135
|
+
if (typeof o.url !== "string")
|
|
136
|
+
throw new Error(`needs "url": the address to look at`);
|
|
137
|
+
const url = new URL(o.url);
|
|
138
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
139
|
+
throw new Error("the address must start with https:// or http://");
|
|
140
|
+
const re = o.match ? pattern(String(o.match)) : undefined;
|
|
141
|
+
source.secret(o.token);
|
|
142
|
+
const guard = o.local === true || isLocal(url) ? undefined : publicOnlyAgent(TIMEOUT);
|
|
143
|
+
if (guard)
|
|
144
|
+
source.onStop(() => guard.close());
|
|
145
|
+
// How many looks in a row failed. Whether "down" was said is kept, so that "up" follows it also across a restart.
|
|
146
|
+
let failed = 0;
|
|
147
|
+
source.poll(o.every ?? "5m", async (signal) => {
|
|
148
|
+
let answer;
|
|
149
|
+
try {
|
|
150
|
+
answer = await get(url, o, guard, signal);
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
if (signal.aborted)
|
|
154
|
+
return;
|
|
155
|
+
const why = reason(e, url);
|
|
156
|
+
failed++;
|
|
157
|
+
if (failed === DOWN_AFTER && !source.kv.get("down")) {
|
|
158
|
+
source.kv.set("down", true);
|
|
159
|
+
source.emit("down", { url: o.url, error: why, looks: failed });
|
|
160
|
+
}
|
|
161
|
+
throw new Error(why);
|
|
162
|
+
}
|
|
163
|
+
failed = 0;
|
|
164
|
+
if (source.kv.get("down")) {
|
|
165
|
+
source.kv.set("down", false);
|
|
166
|
+
source.emit("up", { url: o.url });
|
|
167
|
+
}
|
|
168
|
+
const html = /html/i.test(answer.type) || /^\s*<(!doctype html|html)\b/i.test(answer.body);
|
|
169
|
+
let json;
|
|
170
|
+
if (!html) {
|
|
171
|
+
try {
|
|
172
|
+
json = JSON.parse(answer.body);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
// plain text
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (o.path || re) {
|
|
179
|
+
let value = null;
|
|
180
|
+
if (o.path)
|
|
181
|
+
value = json === undefined ? null : (getPath(json, String(o.path)) ?? null);
|
|
182
|
+
// In what a reader sees first; a pattern that is about the markup finds it in the source.
|
|
183
|
+
else
|
|
184
|
+
value = (html ? found(re, pageText(answer.body)) : null) ?? found(re, answer.body);
|
|
185
|
+
source.status(value === null ? `found nothing ${o.path ? `at ${o.path}` : "with the pattern"}` : `now: ${harmless(value)}`);
|
|
186
|
+
const was = source.changed(value);
|
|
187
|
+
if (was)
|
|
188
|
+
source.emit("changed", { url: o.url, value: shown(value), previous: shown(was.previous) });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const text = (html ? pageText(answer.body) : json !== undefined ? JSON.stringify(json, null, 1) : answer.body).slice(0, 200_000);
|
|
192
|
+
source.status(`now: ${text.split("\n").length} lines`);
|
|
193
|
+
const was = source.changed(text);
|
|
194
|
+
if (!was)
|
|
195
|
+
return;
|
|
196
|
+
const diff = lineDiff(String(was.previous), text);
|
|
197
|
+
// The same lines in another order are not worth a turn.
|
|
198
|
+
if (diff.added.length || diff.removed.length)
|
|
199
|
+
source.emit("changed", { url: o.url, ...diff });
|
|
200
|
+
});
|
|
201
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { SourceType } from "../source-types.ts";
|
|
2
|
+
import type { SourceApi } from "../sources.ts";
|
|
3
|
+
/**
|
|
4
|
+
* An MQTT broker: reports the messages on the topics you name. For home automation hubs, sensors,
|
|
5
|
+
* and devices that speak MQTT themselves (a Bambu printer does, on mqtts://<printer>:8883 with the
|
|
6
|
+
* user "bblp", its access code as password, the topic "device/<serial>/report" and insecureTls).
|
|
7
|
+
*
|
|
8
|
+
* options: { url, topics, publish?, username?, password?, clientId?, minInterval?, insecureTls? }
|
|
9
|
+
* topics one MQTT topic filter or a list ("zigbee2mqtt/+", "device/+/report")
|
|
10
|
+
* publish topics an agent may send to, to act on a device ("zigbee2mqtt/+/set"). Without it nothing can be sent
|
|
11
|
+
* minInterval drop messages that follow the last one on the same topic sooner than this ("30s")
|
|
12
|
+
* insecureTls accept a certificate that cannot be verified, as devices with self-made ones need
|
|
13
|
+
*
|
|
14
|
+
* event "message": { topic, value } value is parsed JSON when the message is JSON, else text
|
|
15
|
+
* It can send, to the topics on `publish` only: { topic, message, retain?, qos? }
|
|
16
|
+
*/
|
|
17
|
+
export declare const type: SourceType;
|
|
18
|
+
export default function mqttSource(source: SourceApi): Promise<void>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { errText, matchesAny, parseDuration } from "../util.js";
|
|
3
|
+
/**
|
|
4
|
+
* An MQTT broker: reports the messages on the topics you name. For home automation hubs, sensors,
|
|
5
|
+
* and devices that speak MQTT themselves (a Bambu printer does, on mqtts://<printer>:8883 with the
|
|
6
|
+
* user "bblp", its access code as password, the topic "device/<serial>/report" and insecureTls).
|
|
7
|
+
*
|
|
8
|
+
* options: { url, topics, publish?, username?, password?, clientId?, minInterval?, insecureTls? }
|
|
9
|
+
* topics one MQTT topic filter or a list ("zigbee2mqtt/+", "device/+/report")
|
|
10
|
+
* publish topics an agent may send to, to act on a device ("zigbee2mqtt/+/set"). Without it nothing can be sent
|
|
11
|
+
* minInterval drop messages that follow the last one on the same topic sooner than this ("30s")
|
|
12
|
+
* insecureTls accept a certificate that cannot be verified, as devices with self-made ones need
|
|
13
|
+
*
|
|
14
|
+
* event "message": { topic, value } value is parsed JSON when the message is JSON, else text
|
|
15
|
+
* It can send, to the topics on `publish` only: { topic, message, retain?, qos? }
|
|
16
|
+
*/
|
|
17
|
+
export const type = {
|
|
18
|
+
summary: "an MQTT broker: reports the messages on the topics you name. For home automation hubs, sensors, and devices that speak MQTT themselves (printers, plugs). With \"publish\" it can also send, to act on a device",
|
|
19
|
+
sends: 'an MQTT message to a topic on its "publish" list, to act on a device: {"topic": "lamp/set", "message": "on"} (message: text or JSON)',
|
|
20
|
+
options: Type.Object({
|
|
21
|
+
url: Type.String({ description: "address of the broker: mqtt://host:1883, or mqtts://host:8883 for TLS" }),
|
|
22
|
+
topics: Type.Union([Type.String(), Type.Array(Type.String())], { description: 'the topic filters to listen to, e.g. "zigbee2mqtt/+" or ["device/+/report"]' }),
|
|
23
|
+
publish: Type.Optional(Type.Array(Type.String(), { description: 'topics you may send to, to act on a device, e.g. ["zigbee2mqtt/+/set"]. Only when your owner wants you to control something; without it nothing can be sent' })),
|
|
24
|
+
username: Type.Optional(Type.String({ description: "user name, if the broker wants one" })),
|
|
25
|
+
password: Type.Optional(Type.String({ description: "password, access code or token, if the broker wants one", secret: true })),
|
|
26
|
+
clientId: Type.Optional(Type.String({ description: "client id, for brokers that want a particular one" })),
|
|
27
|
+
minInterval: Type.Optional(Type.String({ description: 'drop messages that follow the last one on the same topic sooner than this, e.g. "30s". For devices that report many times a second' })),
|
|
28
|
+
insecureTls: Type.Optional(Type.Boolean({ description: "accept a certificate that cannot be verified, as devices with self-made ones need" })),
|
|
29
|
+
}, { additionalProperties: false }),
|
|
30
|
+
plan(o) {
|
|
31
|
+
let url;
|
|
32
|
+
try {
|
|
33
|
+
url = new URL(o.url);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new Error(`"${o.url}" is not an address. An MQTT broker's looks like mqtt://192.168.1.10:1883`);
|
|
37
|
+
}
|
|
38
|
+
if (!["mqtt:", "mqtts:", "ws:", "wss:"].includes(url.protocol))
|
|
39
|
+
throw new Error("an MQTT broker's address starts with mqtt://, mqtts://, ws:// or wss://");
|
|
40
|
+
const topics = (Array.isArray(o.topics) ? o.topics : String(o.topics).split(",")).map((t) => t.trim()).filter(Boolean);
|
|
41
|
+
if (!topics.length)
|
|
42
|
+
throw new Error(`needs "topics": which MQTT topics to listen to`);
|
|
43
|
+
if (o.minInterval)
|
|
44
|
+
parseDuration(o.minInterval);
|
|
45
|
+
const publish = (Array.isArray(o.publish) ? o.publish : []).map((t) => String(t).trim()).filter(Boolean);
|
|
46
|
+
return { options: { ...o, topics, ...(publish.length ? { publish } : {}) }, does: [`connect to the MQTT broker ${url.host}${o.username ? ` as ${o.username}` : ""} and listen to ${topics.join(", ")}`, ...(publish.length ? [`let the agent send messages to ${publish.join(", ")}, which can switch and control devices`] : []), ...(o.password ? ["with the password given"] : []), ...(o.insecureTls ? ["without checking its certificate"] : [])], opens: true };
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
export default async function mqttSource(source) {
|
|
50
|
+
const { default: mqtt } = await import("mqtt");
|
|
51
|
+
const o = source.options;
|
|
52
|
+
if (typeof o.url !== "string")
|
|
53
|
+
throw new Error(`needs "url", for example mqtt://192.168.1.10:1883`);
|
|
54
|
+
const topics = (Array.isArray(o.topics) ? o.topics : o.topics ? [o.topics] : []).map(String);
|
|
55
|
+
if (!topics.length)
|
|
56
|
+
throw new Error(`needs "topics": which MQTT topics to listen to`);
|
|
57
|
+
const minMs = o.minInterval !== undefined ? parseDuration(o.minInterval) : 0;
|
|
58
|
+
source.secret(o.password);
|
|
59
|
+
const client = mqtt.connect(o.url, { username: o.username, password: o.password, clientId: o.clientId ?? `pine-${source.name}-${process.pid}`, reconnectPeriod: 5000, connectTimeout: 10_000, rejectUnauthorized: o.insecureTls !== true });
|
|
60
|
+
source.onStop(() => new Promise((r) => client.end(true, {}, () => r())));
|
|
61
|
+
client.on("error", (e) => source.log.warn("mqtt error", errText(e)));
|
|
62
|
+
client.on("connect", () => {
|
|
63
|
+
source.log.info(`connected to ${new URL(o.url).host}`);
|
|
64
|
+
for (const t of topics)
|
|
65
|
+
client.subscribe(t, (err) => err && source.log.warn(`subscribe ${t} failed`, errText(err)));
|
|
66
|
+
});
|
|
67
|
+
const last = new Map();
|
|
68
|
+
client.on("message", (topic, buf) => {
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
if (minMs && now - (last.get(topic) ?? 0) < minMs)
|
|
71
|
+
return;
|
|
72
|
+
last.set(topic, now);
|
|
73
|
+
if (last.size > 5000)
|
|
74
|
+
last.clear();
|
|
75
|
+
const text = buf.length > 256 * 1024 ? "" : buf.toString("utf8");
|
|
76
|
+
let value = text;
|
|
77
|
+
try {
|
|
78
|
+
value = JSON.parse(text);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// plain text
|
|
82
|
+
}
|
|
83
|
+
source.emit("message", { topic, value });
|
|
84
|
+
});
|
|
85
|
+
// Sending: only to the topics the owner put on the list, and never to a filter.
|
|
86
|
+
const allowed = (Array.isArray(o.publish) ? o.publish : []).map(String);
|
|
87
|
+
source.onSend(async (m) => {
|
|
88
|
+
const topic = String(m.topic ?? "");
|
|
89
|
+
if (!topic)
|
|
90
|
+
throw new Error('say which topic: {"topic": "...", "message": "..."}');
|
|
91
|
+
if (/[+#]/.test(topic) || !matchesAny(allowed, topic))
|
|
92
|
+
throw new Error(`"${topic}" is not a topic this source may send to (${allowed.join(", ") || "none: it was set up to listen only"})`);
|
|
93
|
+
const message = m.message ?? m.text ?? "";
|
|
94
|
+
await new Promise((resolve, reject) => client.publish(topic, typeof message === "string" ? message : JSON.stringify(message), { retain: m.retain === true, qos: [0, 1, 2].includes(m.qos) ? m.qos : 0 }, (err) => (err ? reject(err) : resolve())));
|
|
95
|
+
return `published to ${topic}`;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { SourceType } from "../source-types.ts";
|
|
2
|
+
import type { SourceApi } from "../sources.ts";
|
|
3
|
+
/**
|
|
4
|
+
* A Telegram bot: the owner writes to it from wherever they are, and the agent answers there.
|
|
5
|
+
*
|
|
6
|
+
* options: { token, allow?, approvals?, apiBase? }
|
|
7
|
+
* token the bot's token from @BotFather
|
|
8
|
+
* allow Telegram user ids that may talk to it. Without it the bot is paired: it sends a
|
|
9
|
+
* code to the account that writes to it, and the owner types that code into pine
|
|
10
|
+
* approvals also send approval requests to that chat, with buttons (default true)
|
|
11
|
+
* apiBase a Bot API server of your own instead of api.telegram.org
|
|
12
|
+
*
|
|
13
|
+
* event "message": { text, name, username, chatId, messageId, images? }
|
|
14
|
+
* It can send: { text, chatId? } goes to the owner's chat.
|
|
15
|
+
*
|
|
16
|
+
* Messages are fetched by long polling: one request that Telegram answers the moment something
|
|
17
|
+
* arrives. Nothing listens on a port, so it works behind any router. Only accounts on `allow`, or
|
|
18
|
+
* the one that was paired, are heard. What anyone else writes reaches no agent; once an account
|
|
19
|
+
* is paired they get no answer at all, and nothing is ever sent to them.
|
|
20
|
+
*/
|
|
21
|
+
export declare const type: SourceType;
|
|
22
|
+
export default function telegram(source: SourceApi): Promise<void>;
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Type } from "typebox";
|
|
5
|
+
import { errText, sleep, truncate } from "../util.js";
|
|
6
|
+
/**
|
|
7
|
+
* A Telegram bot: the owner writes to it from wherever they are, and the agent answers there.
|
|
8
|
+
*
|
|
9
|
+
* options: { token, allow?, approvals?, apiBase? }
|
|
10
|
+
* token the bot's token from @BotFather
|
|
11
|
+
* allow Telegram user ids that may talk to it. Without it the bot is paired: it sends a
|
|
12
|
+
* code to the account that writes to it, and the owner types that code into pine
|
|
13
|
+
* approvals also send approval requests to that chat, with buttons (default true)
|
|
14
|
+
* apiBase a Bot API server of your own instead of api.telegram.org
|
|
15
|
+
*
|
|
16
|
+
* event "message": { text, name, username, chatId, messageId, images? }
|
|
17
|
+
* It can send: { text, chatId? } goes to the owner's chat.
|
|
18
|
+
*
|
|
19
|
+
* Messages are fetched by long polling: one request that Telegram answers the moment something
|
|
20
|
+
* arrives. Nothing listens on a port, so it works behind any router. Only accounts on `allow`, or
|
|
21
|
+
* the one that was paired, are heard. What anyone else writes reaches no agent; once an account
|
|
22
|
+
* is paired they get no answer at all, and nothing is ever sent to them.
|
|
23
|
+
*/
|
|
24
|
+
export const type = {
|
|
25
|
+
summary: "a Telegram bot: your owner writes to it from anywhere and you answer there; you can also message them through it. Needs the bot's token from @BotFather",
|
|
26
|
+
talks: true,
|
|
27
|
+
sends: 'a Telegram message to your owner: {"text": "..."}',
|
|
28
|
+
options: Type.Object({
|
|
29
|
+
token: Type.String({ description: "the bot's token, which @BotFather gives when a bot is made with /newbot (123456789:AA...)", secret: true }),
|
|
30
|
+
allow: Type.Optional(Type.Array(Type.Number(), { description: "Telegram user ids that may talk to the bot. Leave out unless your owner gave you their id: the bot is then paired, which means it sends a code to the account that writes to it and your owner types that code into pine" })),
|
|
31
|
+
approvals: Type.Optional(Type.Boolean({ description: "also send approval requests to the owner there, with buttons to answer them. Default true" })),
|
|
32
|
+
apiBase: Type.Optional(Type.String({ description: "address of a Bot API server of your own, instead of https://api.telegram.org" })),
|
|
33
|
+
}, { additionalProperties: false }),
|
|
34
|
+
plan(o) {
|
|
35
|
+
// Without a token yet (the owner is about to be asked for it) there is nothing to check.
|
|
36
|
+
if (o.token !== undefined && !/^\d{5,}:[A-Za-z0-9_-]{20,}$/.test(String(o.token)))
|
|
37
|
+
throw new Error("that is not a bot token. @BotFather gives one that looks like 123456789:AAH... when a bot is created with /newbot");
|
|
38
|
+
if (o.apiBase !== undefined) {
|
|
39
|
+
let url;
|
|
40
|
+
try {
|
|
41
|
+
url = new URL(o.apiBase);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Error(`"${o.apiBase}" is not an address`);
|
|
45
|
+
}
|
|
46
|
+
if (url.protocol !== "https:" && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))
|
|
47
|
+
throw new Error("a Bot API server of your own must be reached over https, or run on this machine");
|
|
48
|
+
}
|
|
49
|
+
const ids = o.allow ?? [];
|
|
50
|
+
return {
|
|
51
|
+
options: o,
|
|
52
|
+
opens: true,
|
|
53
|
+
owner: true,
|
|
54
|
+
does: [
|
|
55
|
+
"connect to Telegram as your bot and wait for messages",
|
|
56
|
+
ids.length ? `listen only to the Telegram user${ids.length === 1 ? "" : "s"} ${ids.join(", ")}` : "listen to nobody until you have paired your own account: the bot sends a code to the account that writes to it, and you type that code into pine",
|
|
57
|
+
"take what that account writes as coming from you, with everything your agents may do for you",
|
|
58
|
+
"send answers back to that chat, and nowhere else",
|
|
59
|
+
...(o.approvals === false ? [] : ["send approval requests there too, with buttons"]),
|
|
60
|
+
],
|
|
61
|
+
tell: ids.length ? "Your owner can write to the bot now." : "Tell your owner to open the bot in Telegram and write anything to it. The bot answers with a six-digit code, and pine asks for that code here. Once they have typed it, that account is the only one the bot listens to.",
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
const MAX_PHOTO = 10 * 1024 * 1024;
|
|
66
|
+
export default async function telegram(source) {
|
|
67
|
+
const o = source.options;
|
|
68
|
+
const token = String(o.token ?? "");
|
|
69
|
+
if (!token)
|
|
70
|
+
throw new Error("the bot token is missing");
|
|
71
|
+
source.secret(token);
|
|
72
|
+
const base = String(o.apiBase ?? "https://api.telegram.org").replace(/\/+$/, "");
|
|
73
|
+
const stop = new AbortController();
|
|
74
|
+
source.onStop(() => stop.abort());
|
|
75
|
+
const api = async (method, body = {}, timeoutMs = 20_000) => {
|
|
76
|
+
const res = await fetch(`${base}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.any([stop.signal, AbortSignal.timeout(timeoutMs)]) });
|
|
77
|
+
const json = await res.json().catch(() => ({}));
|
|
78
|
+
if (!json.ok)
|
|
79
|
+
throw new Error(`Telegram refused ${method}: ${json.description ?? res.status}`);
|
|
80
|
+
return json.result;
|
|
81
|
+
};
|
|
82
|
+
// A wrong token is found out here, and shows as the reason the source is not running.
|
|
83
|
+
const me = await api("getMe");
|
|
84
|
+
const mediaDir = path.join(source.dataDir, "media");
|
|
85
|
+
fs.mkdirSync(mediaDir, { recursive: true });
|
|
86
|
+
source.media(mediaDir);
|
|
87
|
+
// ---- who is heard ------------------------------------------------------------------------------
|
|
88
|
+
const fixed = (Array.isArray(o.allow) ? o.allow : []).map(Number).filter(Number.isFinite);
|
|
89
|
+
const paired = () => source.kv.get("owner");
|
|
90
|
+
const heard = (userId) => fixed.includes(userId) || paired()?.id === userId;
|
|
91
|
+
/** The chat everything unasked goes to. A private chat has the id of its user. */
|
|
92
|
+
const ownerChat = () => fixed[0] ?? paired()?.id;
|
|
93
|
+
/** Who may talk to the bot, said where the sources are listed. */
|
|
94
|
+
const say = () => source.status(fixed.length
|
|
95
|
+
? `@${me.username} listens only to the Telegram user${fixed.length === 1 ? "" : "s"} ${fixed.join(", ")}`
|
|
96
|
+
: paired()
|
|
97
|
+
? `@${me.username} listens only to ${paired().name || "the paired account"} (Telegram id ${paired().id}), which you confirmed`
|
|
98
|
+
: `@${me.username} listens to nobody yet: write to it from your Telegram account, then type the code it sends you into pine`);
|
|
99
|
+
say();
|
|
100
|
+
const send = async (chatId, text, extra = {}) => {
|
|
101
|
+
if (!heard(chatId))
|
|
102
|
+
throw new Error("that chat is not your owner's");
|
|
103
|
+
const body = text.trim() || "(empty message)";
|
|
104
|
+
let last;
|
|
105
|
+
for (let i = 0; i < body.length; i += 4000)
|
|
106
|
+
last = await api("sendMessage", { chat_id: chatId, text: body.slice(i, i + 4000), ...(i + 4000 >= body.length ? extra : {}) });
|
|
107
|
+
return last;
|
|
108
|
+
};
|
|
109
|
+
// ---- out: answers, and what an agent sends on its own -------------------------------------------
|
|
110
|
+
source.onSend(async (message) => {
|
|
111
|
+
const chatId = Number(message.chatId ?? ownerChat());
|
|
112
|
+
if (!Number.isFinite(chatId))
|
|
113
|
+
throw new Error("nobody is connected yet: your owner has to write to the bot once, and confirm it in pine");
|
|
114
|
+
await send(chatId, String(message.text ?? ""));
|
|
115
|
+
return "sent to your owner on Telegram";
|
|
116
|
+
});
|
|
117
|
+
// "typing…" while an agent works on something that will be answered here.
|
|
118
|
+
const typing = new Map();
|
|
119
|
+
source.on("agent/+/started", (e) => {
|
|
120
|
+
const p = e.payload;
|
|
121
|
+
const chatId = Number(p?.reply?.payload?.chatId);
|
|
122
|
+
if (p?.reply?.topic !== `out/source/${source.key}` || !heard(chatId))
|
|
123
|
+
return;
|
|
124
|
+
const tick = () => void api("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => { });
|
|
125
|
+
tick();
|
|
126
|
+
const h = setInterval(tick, 4500);
|
|
127
|
+
h.unref?.();
|
|
128
|
+
typing.set(p.task, h);
|
|
129
|
+
});
|
|
130
|
+
source.on(["agent/+/done", "agent/+/failed"], (e) => {
|
|
131
|
+
const id = e.payload?.task;
|
|
132
|
+
clearInterval(typing.get(id));
|
|
133
|
+
typing.delete(id);
|
|
134
|
+
});
|
|
135
|
+
source.onStop(() => typing.forEach((h) => clearInterval(h)));
|
|
136
|
+
// ---- approval requests, to answer from the phone ---------------------------------------------------
|
|
137
|
+
if (o.approvals !== false) {
|
|
138
|
+
const asked = new Map();
|
|
139
|
+
source.on("approval/requested", async (e) => {
|
|
140
|
+
const r = e.payload;
|
|
141
|
+
const chat = ownerChat();
|
|
142
|
+
if (chat === undefined)
|
|
143
|
+
return;
|
|
144
|
+
// A question of the agent's with answers to pick from: one button each. (Their own words they type on their machine.)
|
|
145
|
+
if (r.tool === "question" && Array.isArray(r.choices) && r.choices.length) {
|
|
146
|
+
const rows = r.choices.slice(0, 6).map((c, i) => [{ text: truncate(String(c), 60), callback_data: `ap:${r.id}:c${i}` }]);
|
|
147
|
+
const msg = await send(chat, `${r.agent} asks:\n${truncate(String(r.summary), 1200)}`, { reply_markup: { inline_keyboard: [...rows, [{ text: "No answer", callback_data: `ap:${r.id}:0` }]] } });
|
|
148
|
+
if (msg?.message_id)
|
|
149
|
+
asked.set(r.id, msg.message_id);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
// A question the owner answers by typing a secret belongs on their own machine, not in a chat.
|
|
153
|
+
if (r.inputs?.length)
|
|
154
|
+
return;
|
|
155
|
+
const always = r.remember ? [{ text: `Always: ${truncate(String(r.remember), 30)}`, callback_data: `ap:${r.id}:2` }] : [];
|
|
156
|
+
const msg = await send(chat, `Approval needed\nAgent: ${r.agent}${r.task ? ` (task #${r.task})` : ""}\nAction: ${truncate(String(r.summary), 1200)}\nWhy you are asked: ${r.why}`, { reply_markup: { inline_keyboard: [[{ text: "Allow", callback_data: `ap:${r.id}:1` }, ...always, { text: "Deny", callback_data: `ap:${r.id}:0` }]] } });
|
|
157
|
+
if (msg?.message_id)
|
|
158
|
+
asked.set(r.id, msg.message_id);
|
|
159
|
+
});
|
|
160
|
+
source.on("approval/decided", async (e) => {
|
|
161
|
+
const d = e.payload;
|
|
162
|
+
const messageId = asked.get(d.id);
|
|
163
|
+
asked.delete(d.id);
|
|
164
|
+
if (messageId)
|
|
165
|
+
await api("editMessageReplyMarkup", { chat_id: ownerChat(), message_id: messageId, reply_markup: { inline_keyboard: [[{ text: d.tool === "question" ? (d.allow ? `Answered (${d.by})` : `No answer (${d.by})`) : d.allow ? `Allowed (${d.by})` : `Denied (${d.by})`, callback_data: "noop" }]] } }).catch(() => { });
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
// ---- in ----------------------------------------------------------------------------------------
|
|
169
|
+
const photo = async (sizes) => {
|
|
170
|
+
const best = sizes.filter((s) => (s.file_size ?? 0) <= MAX_PHOTO).at(-1);
|
|
171
|
+
if (!best)
|
|
172
|
+
return undefined;
|
|
173
|
+
const file = await api("getFile", { file_id: best.file_id });
|
|
174
|
+
const res = await fetch(`${base}/file/bot${token}/${file.file_path}`, { signal: AbortSignal.timeout(30_000) });
|
|
175
|
+
if (!res.ok)
|
|
176
|
+
return undefined;
|
|
177
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
178
|
+
if (buf.length > MAX_PHOTO)
|
|
179
|
+
return undefined;
|
|
180
|
+
const target = path.join(mediaDir, `${String(best.file_unique_id).replace(/[^A-Za-z0-9_-]/g, "")}.jpg`);
|
|
181
|
+
fs.writeFileSync(target, buf, { mode: 0o600 });
|
|
182
|
+
return { path: target, mimeType: "image/jpeg" };
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* An account nobody knows yet writes to a bot that has no owner. Whoever sits at pine has to
|
|
186
|
+
* show that this account is theirs: the bot sends the account a code, and pine asks for it.
|
|
187
|
+
* A press of a key cannot say yes to a stranger, and a stranger does not know what to type.
|
|
188
|
+
* One question at a time; an account the owner turned down is not asked about again.
|
|
189
|
+
*/
|
|
190
|
+
let pairing = false;
|
|
191
|
+
const pair = async (m, userId, name) => {
|
|
192
|
+
const denied = source.kv.get("denied") ?? [];
|
|
193
|
+
if (fixed.length || paired() || pairing || denied.includes(userId))
|
|
194
|
+
return false;
|
|
195
|
+
pairing = true;
|
|
196
|
+
try {
|
|
197
|
+
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
|
|
198
|
+
const shown = `${code.slice(0, 3)} ${code.slice(3)}`;
|
|
199
|
+
await api("sendMessage", { chat_id: userId, text: `To connect this Telegram account to pine, type this code into the question pine is showing on your computer:\n\n${shown}\n\nIf you did not expect this message, ignore it.` });
|
|
200
|
+
const who = `${name || "somebody"} (${m.from?.username ? `@${m.from.username}, ` : ""}Telegram id ${userId})`;
|
|
201
|
+
const answer = await source.approvals.request(`let the Telegram account of ${who} talk to your agents as you through the bot @${me.username}\nIt just wrote: "${truncate(String(m.text ?? m.caption ?? "(a picture)"), 200)}"\nThe bot sent that account a code. If the account is yours, the code is on your phone now.`, "what this account writes will count as your own words, with everything your agents may do for you. Only the code proves that the account is yours; deny it if you did not just write to the bot", [{ name: "code", label: "code: the six digits the bot just sent to that account in Telegram", secret: false }]);
|
|
202
|
+
if (!answer.allow) {
|
|
203
|
+
// Turned down by the owner (not merely unanswered): that account is not put to them again.
|
|
204
|
+
if (answer.by !== "timeout" && answer.by !== "aborted")
|
|
205
|
+
source.kv.set("denied", [...denied, userId].slice(-200));
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
if (String(answer.values?.code ?? "").replace(/\D/g, "") !== code) {
|
|
209
|
+
await api("sendMessage", { chat_id: userId, text: "That was not the code. Write again to get a new one." }).catch(() => { });
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
if (!paired())
|
|
213
|
+
source.kv.set("owner", { id: userId, name: `${name}${m.from?.username ? ` (@${m.from.username})` : ""}` });
|
|
214
|
+
say();
|
|
215
|
+
return paired()?.id === userId;
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
pairing = false;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
const onMessage = async (m) => {
|
|
222
|
+
const userId = Number(m.from?.id);
|
|
223
|
+
const chatId = Number(m.chat?.id);
|
|
224
|
+
const name = [m.from?.first_name, m.from?.last_name].filter(Boolean).join(" ");
|
|
225
|
+
if (m.chat?.type !== "private")
|
|
226
|
+
return;
|
|
227
|
+
// Unknown senders get no answer at all: nothing to probe, nothing to flood the log with.
|
|
228
|
+
if (!heard(userId) && !(await pair(m, userId, name)))
|
|
229
|
+
return source.log.debug(`ignored a message from user ${userId}`);
|
|
230
|
+
const text = String(m.text || m.caption || "").trim();
|
|
231
|
+
const images = m.photo ? [await photo(m.photo).catch(() => undefined)].filter(Boolean) : [];
|
|
232
|
+
if (!text && !images.length)
|
|
233
|
+
return;
|
|
234
|
+
const verdict = text.match(/^\/(allow|deny)(?:\s+(\w+))?/);
|
|
235
|
+
if (verdict && o.approvals !== false) {
|
|
236
|
+
const pending = source.approvals.pending();
|
|
237
|
+
const id = verdict[2] ?? (pending.length === 1 ? pending[0].id : undefined);
|
|
238
|
+
const ok = id ? source.approvals.decide(id, verdict[1] === "allow", `telegram:${userId}`) : false;
|
|
239
|
+
return void send(chatId, ok ? "Noted." : "No such open request.").catch(() => { });
|
|
240
|
+
}
|
|
241
|
+
source.emit("message", { text: text || "(a picture)", name, username: m.from?.username, chatId, messageId: m.message_id, images: images.length ? images : undefined }, { reply: { chatId } });
|
|
242
|
+
};
|
|
243
|
+
const onCallback = async (c) => {
|
|
244
|
+
const userId = Number(c.from?.id);
|
|
245
|
+
const m = String(c.data ?? "").match(/^ap:(\w+):([012]|c\d)$/);
|
|
246
|
+
if (!heard(userId) || !m)
|
|
247
|
+
return void api("answerCallbackQuery", { callback_query_id: c.id }).catch(() => { });
|
|
248
|
+
if (m[2].startsWith("c")) {
|
|
249
|
+
const chosen = source.approvals.choose(m[1], Number(m[2].slice(1)), `telegram:${userId}`);
|
|
250
|
+
return void api("answerCallbackQuery", { callback_query_id: c.id, text: chosen ? "Answered" : "Already answered or expired" }).catch(() => { });
|
|
251
|
+
}
|
|
252
|
+
const ok = source.approvals.decide(m[1], m[2] !== "0", `telegram:${userId}`, m[2] === "2");
|
|
253
|
+
await api("answerCallbackQuery", { callback_query_id: c.id, text: ok ? (m[2] === "0" ? "Denied" : m[2] === "2" ? "Allowed for this conversation" : "Allowed") : "Already answered or expired" }).catch(() => { });
|
|
254
|
+
};
|
|
255
|
+
const poll = async () => {
|
|
256
|
+
const pollSec = 25;
|
|
257
|
+
let offset = source.kv.get("offset") ?? 0;
|
|
258
|
+
let backoff = 1000;
|
|
259
|
+
while (!stop.signal.aborted) {
|
|
260
|
+
try {
|
|
261
|
+
const updates = await api("getUpdates", { offset, timeout: pollSec, allowed_updates: ["message", "callback_query"] }, (pollSec + 10) * 1000);
|
|
262
|
+
backoff = 1000;
|
|
263
|
+
for (const u of updates) {
|
|
264
|
+
offset = u.update_id + 1;
|
|
265
|
+
source.kv.set("offset", offset);
|
|
266
|
+
// Not awaited: a pairing question stays open until the owner answers, and messages keep coming meanwhile.
|
|
267
|
+
if (u.message)
|
|
268
|
+
void onMessage(u.message).catch((e) => source.log.warn("a message could not be handled", errText(e)));
|
|
269
|
+
else if (u.callback_query)
|
|
270
|
+
void onCallback(u.callback_query).catch((e) => source.log.warn("a button press could not be handled", errText(e)));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
if (stop.signal.aborted)
|
|
275
|
+
break;
|
|
276
|
+
source.log.warn(`asking Telegram for messages failed, trying again in ${backoff} ms`, errText(e));
|
|
277
|
+
await sleep(backoff);
|
|
278
|
+
backoff = Math.min(backoff * 2, 60_000);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
void poll();
|
|
283
|
+
}
|