hyperclaw 5.0.0 → 5.0.2
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 +2 -1
- package/README.md +449 -99
- package/dist/a2ui-protocol-Gzm29Gaw.js +75 -0
- package/dist/agents-routing-Biy5ew4a.js +4 -0
- package/dist/agents-routing-CL3HQNoM.js +327 -0
- package/dist/api-keys-guide-CGn5BSF7.js +149 -0
- package/dist/api-keys-guide-ChbThbPj.js +149 -0
- package/dist/audit-BJohI_vC.js +441 -0
- package/dist/audit-NPIMmOSq.js +441 -0
- package/dist/bounty-tools-BUqUKjt0.js +211 -0
- package/dist/bounty-tools-CY_i91DU.js +211 -0
- package/dist/browser-tools-CxJY6pAn.js +5 -0
- package/dist/browser-tools-JZ9ji6AW.js +179 -0
- package/dist/chat-qVuqhlPu.js +258 -0
- package/dist/claw-tasks-B-8RRMdq.js +80 -0
- package/dist/claw-tasks-Cyzdbhz_.js +80 -0
- package/dist/connector-1x1rCBHz.js +162 -0
- package/dist/connector-B4jeCULG.js +305 -0
- package/dist/connector-B7qngfkT.js +286 -0
- package/dist/connector-B8BK0GBo.js +531 -0
- package/dist/connector-BE9eJs8-.js +182 -0
- package/dist/connector-BEe-DTGQ.js +189 -0
- package/dist/connector-BU7p5ZgB.js +167 -0
- package/dist/connector-BUzzq7Ij.js +568 -0
- package/dist/connector-BpDqLgnW.js +419 -0
- package/dist/connector-BpW88ut2.js +189 -0
- package/dist/connector-Bxv-gy8U.js +167 -0
- package/dist/connector-Bz14zcJv.js +213 -0
- package/dist/connector-C1zP5-5q.js +85 -0
- package/dist/connector-CAcpcovF.js +498 -0
- package/dist/connector-CJgVjS58.js +181 -0
- package/dist/connector-Cf53D6qV.js +425 -0
- package/dist/connector-CyHmlbNz.js +508 -0
- package/dist/connector-D22mJGVu.js +340 -0
- package/dist/connector-D6RtMmlL.js +225 -0
- package/dist/connector-D9EnT8A4.js +280 -0
- package/dist/connector-DNDwIh37.js +239 -0
- package/dist/connector-Di27MeO4.js +350 -0
- package/dist/connector-Do0BPiHt.js +194 -0
- package/dist/connector-DvLwOfJy.js +192 -0
- package/dist/connector-DvU83NSq.js +181 -0
- package/dist/connector-DxskpDc_.js +173 -0
- package/dist/connector-byy3eISx.js +552 -0
- package/dist/connector-vV89hsyd.js +218 -0
- package/dist/cost-tracker-Ca1UPZ33.js +103 -0
- package/dist/cost-tracker-fnaj_6M9.js +103 -0
- package/dist/credentials-store-BxijEirw.js +77 -0
- package/dist/credentials-store-CA8UtK0T.js +77 -0
- package/dist/credentials-store-CPkVO6-z.js +4 -0
- package/dist/credentials-store-Cm7DH-kh.js +4 -0
- package/dist/cron-tasks-L0mz1yyU.js +82 -0
- package/dist/cron-tasks-_pqQCmxc.js +82 -0
- package/dist/daemon-7ViroziB.js +5 -0
- package/dist/daemon-BfyKmZhr.js +318 -0
- package/dist/daemon-CNyunwkR.js +5 -0
- package/dist/daemon-CindY8OK.js +318 -0
- package/dist/delivery-DVHmv1IR.js +4 -0
- package/dist/delivery-DgiZcJBp.js +4 -0
- package/dist/delivery-DpMX0Yyc.js +95 -0
- package/dist/delivery-otAU4alM.js +95 -0
- package/dist/destructive-gate-CA0DtA5K.js +101 -0
- package/dist/destructive-gate-DZt71UZR.js +101 -0
- package/dist/developer-keys-Cnd1kswV.js +127 -0
- package/dist/developer-keys-DENo3ZA6.js +8 -0
- package/dist/doctor-Dgjoc3DG.js +230 -0
- package/dist/doctor-RwsOhtAl.js +6 -0
- package/dist/engine-B0kLfRL0.js +256 -0
- package/dist/engine-BJUpRUOv.js +7 -0
- package/dist/engine-D_VeoZHw.js +305 -0
- package/dist/engine-JjRnhlsE.js +7 -0
- package/dist/env-resolve-17ekEU6p.js +10 -0
- package/dist/env-resolve-BFJXWl94.js +115 -0
- package/dist/env-resolve-Z2XF6leB.js +115 -0
- package/dist/env-resolve-bDYssfih.js +10 -0
- package/dist/extraction-tools-DbxnxIco.js +5 -0
- package/dist/extraction-tools-Dg7AHS35.js +91 -0
- package/dist/form_data-CGAy4HE0.js +8657 -0
- package/dist/gmail-watch-setup-C3uSWznp.js +40 -0
- package/dist/health-DUjluWHQ.js +6 -0
- package/dist/health-DVfkpUQW.js +152 -0
- package/dist/heartbeat-engine-CrgL4mrP.js +83 -0
- package/dist/heartbeat-engine-Ut6pXBD6.js +83 -0
- package/dist/hub-9LaKnLjY.js +6 -0
- package/dist/hub-BO6bj8Yj.js +515 -0
- package/dist/hub-Bu52YZqW.js +6 -0
- package/dist/hub-CfwUz9YW.js +515 -0
- package/dist/hyperclawbot-BrcoYLOp.js +505 -0
- package/dist/hyperclawbot-CBiDSKsa.js +505 -0
- package/dist/inference-0mlFQqIm.js +922 -0
- package/dist/inference-DHR82Gh7.js +6 -0
- package/dist/inference-DhA8jpfH.js +2692 -0
- package/dist/inference-SzqFe_nk.js +6 -0
- package/dist/knowledge-graph-BrYpSgxW.js +131 -0
- package/dist/knowledge-graph-DE5lSF02.js +131 -0
- package/dist/loader-9JqY6Nlq.js +4 -0
- package/dist/loader-BkDi8MD9.js +400 -0
- package/dist/loader-Cjdd1kw4.js +400 -0
- package/dist/loader-DI2qDRPC.js +4 -0
- package/dist/logger-Cp8wC7F8.js +83 -0
- package/dist/logger-DCT2l9GV.js +83 -0
- package/dist/manager-3cq3DydI.js +4 -0
- package/dist/manager-B2Gls5RG.js +218 -0
- package/dist/manager-BUrFrPuq.js +117 -0
- package/dist/manager-Bi9UYyVR.js +105 -0
- package/dist/manager-Biz9ixWJ.js +40 -0
- package/dist/manager-CBUHJiY7.js +6 -0
- package/dist/manager-CVLLaKmq.js +218 -0
- package/dist/manager-CWNSML5D.js +117 -0
- package/dist/manager-SJe9gt-q.js +4 -0
- package/dist/mcp-CUoTCMw-.js +139 -0
- package/dist/mcp-loader-BIz-450x.js +94 -0
- package/dist/mcp-loader-CvxRDtPC.js +94 -0
- package/dist/memory-OL77OMOr.js +270 -0
- package/dist/memory-auto-CpQHZlEJ.js +306 -0
- package/dist/memory-auto-D-L2q21G.js +306 -0
- package/dist/memory-auto-DTcy5VBy.js +5 -0
- package/dist/memory-auto-Z6LCf-iK.js +5 -0
- package/dist/memory-gUi4VaIf.js +4 -0
- package/dist/memory-integration-B8RSN4pr.js +91 -0
- package/dist/memory-integration-g2vxwgoE.js +91 -0
- package/dist/moltbook-B-40gQOL.js +81 -0
- package/dist/moltbook-Cl8cQfxJ.js +81 -0
- package/dist/node-TWxRm84k.js +222 -0
- package/dist/nodes-registry-C9dCFwjh.js +52 -0
- package/dist/nodes-registry-DKRtsbNg.js +52 -0
- package/dist/oauth-flow-CeaaGAz0.js +150 -0
- package/dist/oauth-flow-JCfporKq.js +150 -0
- package/dist/oauth-provider-4R0EJlsT.js +110 -0
- package/dist/oauth-provider-B4dzn56l.js +110 -0
- package/dist/observability-CDZmeHfa.js +89 -0
- package/dist/observability-nZ3CBIxG.js +89 -0
- package/dist/onboard-BBBWcfhp.js +10 -0
- package/dist/onboard-BVOtKQdh.js +3641 -0
- package/dist/onboard-Bw28IRQ3.js +4070 -0
- package/dist/onboard-CGNIw27w.js +11 -0
- package/dist/orchestrator-BovkM63z.js +6 -0
- package/dist/orchestrator-CcKx1Ovk.js +189 -0
- package/dist/orchestrator-DSbpkP1X.js +189 -0
- package/dist/orchestrator-DcFfDLTX.js +6 -0
- package/dist/osint-B4_m3VHQ.js +277 -0
- package/dist/osint-B6BZKQAD.js +277 -0
- package/dist/pairing-B6RArWhD.js +196 -0
- package/dist/pairing-BsQ08DLq.js +4 -0
- package/dist/pc-access-B0KocJNe.js +819 -0
- package/dist/pc-access-DkzmugZ7.js +8 -0
- package/dist/pending-approval-BgNjjuI2.js +22 -0
- package/dist/pending-approval-C_HkX1QL.js +22 -0
- package/dist/providers-DxiamZSL.js +5 -0
- package/dist/providers-Dy15rDb7.js +657 -0
- package/dist/reminders-store-CzUY0zYx.js +58 -0
- package/dist/renderer-ANNfXsHn.js +225 -0
- package/dist/rules-BSQwwAYC.js +103 -0
- package/dist/run-main.js +142 -132
- package/dist/runner-BHRSOPEU.js +1271 -0
- package/dist/runner-CJFJUtPm.js +1271 -0
- package/dist/sdk/index.js +2 -2
- package/dist/sdk/index.mjs +2 -2
- package/dist/security--oQObeJO.js +4 -0
- package/dist/security-wBOg0TA8.js +73 -0
- package/dist/server-Brl_HQUB.js +1255 -0
- package/dist/server-CbTTpB5m.js +1255 -0
- package/dist/server-DP_bPzvI.js +4 -0
- package/dist/server-DhfipkwN.js +4 -0
- package/dist/session-store-B09r5HgB.js +5 -0
- package/dist/session-store-DCTQIVur.js +113 -0
- package/dist/sessions-tools-BdlN6Pb6.js +95 -0
- package/dist/sessions-tools-JVLDKSJ_.js +5 -0
- package/dist/skill-loader-B5oeliGu.js +7 -0
- package/dist/skill-loader-Wf3brNOj.js +160 -0
- package/dist/skill-runtime-BGlvly2s.js +102 -0
- package/dist/skill-runtime-BXWd-Ktf.js +102 -0
- package/dist/skill-runtime-DhL2T76p.js +5 -0
- package/dist/skill-runtime-jgklm02e.js +5 -0
- package/dist/src-BbPa6Q8p.js +63 -0
- package/dist/src-BeXtfkK2.js +458 -0
- package/dist/src-Bhybpk1J.js +63 -0
- package/dist/src-CGQjRI4N.js +20 -0
- package/dist/src-DMJ4-uqk.js +458 -0
- package/dist/sub-agent-tools-CmE345s_.js +39 -0
- package/dist/sub-agent-tools-DHY-4WWM.js +39 -0
- package/dist/theme-D0smfC_l.js +8 -0
- package/dist/theme-DajRRZbA.js +180 -0
- package/dist/tool-policy-DZvF8xlQ.js +189 -0
- package/dist/tool-policy-DgNqFWYn.js +189 -0
- package/dist/tts-elevenlabs-C06nUxMK.js +61 -0
- package/dist/tts-elevenlabs-JeFaGNJU.js +61 -0
- package/dist/update-check-BVEqHhFY.js +83 -0
- package/dist/update-check-w4XuxVl7.js +81 -0
- package/dist/vision-JOtOS1Br.js +121 -0
- package/dist/vision-fky3elEo.js +121 -0
- package/dist/vision-tools-C8B3776g.js +5 -0
- package/dist/vision-tools-CB28ZCO_.js +5 -0
- package/dist/vision-tools-dwn9p4el.js +51 -0
- package/dist/vision-tools-vPPwQ-0N.js +51 -0
- package/dist/voice-transcription-B6RtplmN.js +138 -0
- package/dist/voice-transcription-DBo5hXmu.js +138 -0
- package/dist/website-watch-tools-B-jRAeTe.js +139 -0
- package/dist/website-watch-tools-BC9xAL67.js +5 -0
- package/package.json +1 -1
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-jS-bbMI5.js');
|
|
2
|
+
const chalk = require_chunk.__toESM(require("chalk"));
|
|
3
|
+
const fs_extra = require_chunk.__toESM(require("fs-extra"));
|
|
4
|
+
const path = require_chunk.__toESM(require("path"));
|
|
5
|
+
const os = require_chunk.__toESM(require("os"));
|
|
6
|
+
const crypto = require_chunk.__toESM(require("crypto"));
|
|
7
|
+
const http = require_chunk.__toESM(require("http"));
|
|
8
|
+
const ws = require_chunk.__toESM(require("ws"));
|
|
9
|
+
const https = require_chunk.__toESM(require("https"));
|
|
10
|
+
const events = require_chunk.__toESM(require("events"));
|
|
11
|
+
|
|
12
|
+
//#region extensions/mattermost/src/connector.ts
|
|
13
|
+
const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "mattermost-state.json");
|
|
14
|
+
const HMAC_INTERACTIONS_KEY = "openclaw-mattermost-interactions";
|
|
15
|
+
const WS_RECONNECT_DELAY_MS = 5e3;
|
|
16
|
+
async function mmApi(baseUrl, token, method, apiPath, body) {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
19
|
+
const fullPath = apiPath.startsWith("/") ? apiPath : `/${apiPath}`;
|
|
20
|
+
const url = new URL(fullPath, base);
|
|
21
|
+
const payload = body ? JSON.stringify(body) : null;
|
|
22
|
+
const client = url.protocol === "https:" ? https.default : http.default;
|
|
23
|
+
const req = client.request({
|
|
24
|
+
hostname: url.hostname,
|
|
25
|
+
port: url.port || (url.protocol === "https:" ? 443 : 80),
|
|
26
|
+
path: url.pathname + (url.search || ""),
|
|
27
|
+
method,
|
|
28
|
+
headers: {
|
|
29
|
+
Authorization: `Bearer ${token}`,
|
|
30
|
+
...payload ? {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
"Content-Length": Buffer.byteLength(payload)
|
|
33
|
+
} : {}
|
|
34
|
+
}
|
|
35
|
+
}, (res) => {
|
|
36
|
+
let data = "";
|
|
37
|
+
res.on("data", (c) => data += c);
|
|
38
|
+
res.on("end", () => {
|
|
39
|
+
try {
|
|
40
|
+
const r = data ? JSON.parse(data) : {};
|
|
41
|
+
const ok = res.statusCode !== void 0 && res.statusCode >= 200 && res.statusCode < 300;
|
|
42
|
+
if (ok) resolve(r);
|
|
43
|
+
else reject(new Error(r.message || r.error || `HTTP ${res.statusCode}`));
|
|
44
|
+
} catch (e) {
|
|
45
|
+
reject(e || new Error("Parse error"));
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
req.on("error", reject);
|
|
50
|
+
if (payload) req.write(payload);
|
|
51
|
+
req.end();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function deriveInteractionSecret(botToken) {
|
|
55
|
+
return crypto.default.createHmac("sha256", HMAC_INTERACTIONS_KEY).update(botToken).digest("hex");
|
|
56
|
+
}
|
|
57
|
+
function signContext(ctx, secret) {
|
|
58
|
+
const sortedKeys = Object.keys(ctx).sort();
|
|
59
|
+
const payload = {};
|
|
60
|
+
for (const k of sortedKeys) payload[k] = ctx[k];
|
|
61
|
+
const serialized = JSON.stringify(payload);
|
|
62
|
+
return crypto.default.createHmac("sha256", secret).update(serialized).digest("hex");
|
|
63
|
+
}
|
|
64
|
+
function verifyInteraction(context, secret) {
|
|
65
|
+
const token = context["_token"];
|
|
66
|
+
if (typeof token !== "string") return false;
|
|
67
|
+
const { _token: _,...rest } = context;
|
|
68
|
+
return signContext(rest, secret) === token;
|
|
69
|
+
}
|
|
70
|
+
function resolveAccount(id, raw, state) {
|
|
71
|
+
const botToken = raw.botToken || raw.token || process.env["MATTERMOST_BOT_TOKEN"] || "";
|
|
72
|
+
const baseUrl = raw.baseUrl || raw.serverUrl || process.env["MATTERMOST_URL"] || "";
|
|
73
|
+
return {
|
|
74
|
+
id,
|
|
75
|
+
name: raw.name ?? id,
|
|
76
|
+
botToken,
|
|
77
|
+
baseUrl: baseUrl.replace(/\/$/, ""),
|
|
78
|
+
dmPolicy: raw.dmPolicy ?? "pairing",
|
|
79
|
+
allowFrom: raw.allowFrom ?? [],
|
|
80
|
+
groupPolicy: raw.groupPolicy ?? "allowlist",
|
|
81
|
+
groupAllowFrom: raw.groupAllowFrom ?? [],
|
|
82
|
+
dangerouslyAllowNameMatching: raw.dangerouslyAllowNameMatching ?? false,
|
|
83
|
+
chatmode: raw.chatmode ?? "oncall",
|
|
84
|
+
oncharPrefixes: raw.oncharPrefixes ?? [">"],
|
|
85
|
+
requireMention: raw.requireMention ?? true,
|
|
86
|
+
commands: raw.commands ?? { native: false },
|
|
87
|
+
capabilities: raw.capabilities ?? [],
|
|
88
|
+
actions: {
|
|
89
|
+
reactions: true,
|
|
90
|
+
...raw.actions
|
|
91
|
+
},
|
|
92
|
+
interactions: raw.interactions ?? {},
|
|
93
|
+
approvedPairings: state.approved,
|
|
94
|
+
pendingPairings: state.pending
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
var SingleAccountConnector = class extends events.EventEmitter {
|
|
98
|
+
acc;
|
|
99
|
+
ws = null;
|
|
100
|
+
wsSeq = 1;
|
|
101
|
+
reconnecting = false;
|
|
102
|
+
botUserId = "";
|
|
103
|
+
constructor(acc) {
|
|
104
|
+
super();
|
|
105
|
+
this.acc = acc;
|
|
106
|
+
}
|
|
107
|
+
async connect() {
|
|
108
|
+
const me = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", "/api/v4/users/me");
|
|
109
|
+
this.botUserId = me.id;
|
|
110
|
+
console.log(chalk.default.green(` 🦅 Mattermost[${this.acc.id}]: connected as @${me.username} → ${this.acc.baseUrl}`));
|
|
111
|
+
this._startWebSocket();
|
|
112
|
+
this.emit("connected", {
|
|
113
|
+
accountId: this.acc.id,
|
|
114
|
+
baseUrl: this.acc.baseUrl,
|
|
115
|
+
botUserId: this.botUserId
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
disconnect() {
|
|
119
|
+
this.reconnecting = false;
|
|
120
|
+
this.ws?.close();
|
|
121
|
+
this.ws = null;
|
|
122
|
+
}
|
|
123
|
+
_startWebSocket() {
|
|
124
|
+
const wsUrl = this.acc.baseUrl.replace(/^http/, "ws") + "/api/v4/websocket";
|
|
125
|
+
const ws$1 = new ws.default(wsUrl);
|
|
126
|
+
this.ws = ws$1;
|
|
127
|
+
ws$1.on("open", () => {
|
|
128
|
+
this.wsSeq = 1;
|
|
129
|
+
ws$1.send(JSON.stringify({
|
|
130
|
+
seq: this.wsSeq++,
|
|
131
|
+
action: "authentication_challenge",
|
|
132
|
+
data: { token: this.acc.botToken }
|
|
133
|
+
}));
|
|
134
|
+
});
|
|
135
|
+
ws$1.on("message", (raw) => {
|
|
136
|
+
try {
|
|
137
|
+
const ev = JSON.parse(raw.toString());
|
|
138
|
+
if (ev.event === "posted") this._onPostedEvent(ev);
|
|
139
|
+
if (ev.event === "reaction_added" || ev.event === "reaction_removed") this.emit("reaction", {
|
|
140
|
+
accountId: this.acc.id,
|
|
141
|
+
event: ev.event,
|
|
142
|
+
data: ev.data
|
|
143
|
+
});
|
|
144
|
+
} catch {}
|
|
145
|
+
});
|
|
146
|
+
ws$1.on("close", () => {
|
|
147
|
+
if (!this.reconnecting) return;
|
|
148
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${this.acc.id}]: WS closed, reconnecting...`));
|
|
149
|
+
setTimeout(() => this._startWebSocket(), WS_RECONNECT_DELAY_MS);
|
|
150
|
+
});
|
|
151
|
+
ws$1.on("error", (err) => {
|
|
152
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${this.acc.id}]: WS error: ${err.message}`));
|
|
153
|
+
});
|
|
154
|
+
this.reconnecting = true;
|
|
155
|
+
}
|
|
156
|
+
_onPostedEvent(ev) {
|
|
157
|
+
let post;
|
|
158
|
+
try {
|
|
159
|
+
post = typeof ev.data?.post === "string" ? JSON.parse(ev.data.post) : ev.data?.post;
|
|
160
|
+
} catch {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (!post) return;
|
|
164
|
+
if (post.user_id === this.botUserId) return;
|
|
165
|
+
const channelType = ev.data?.channel_type ?? "";
|
|
166
|
+
const isDM = channelType === "D";
|
|
167
|
+
const text = (post.message || "").trim();
|
|
168
|
+
const from = post.user_id;
|
|
169
|
+
const channelId = post.channel_id;
|
|
170
|
+
const senderName = ev.data?.sender_name ?? "";
|
|
171
|
+
if (!text) return;
|
|
172
|
+
if (isDM) this._routeDM(from, channelId, text, senderName, post.id);
|
|
173
|
+
else this._routeChannel(from, channelId, text, senderName, post.id);
|
|
174
|
+
}
|
|
175
|
+
async _routeDM(userId, channelId, text, senderName, postId) {
|
|
176
|
+
const acc = this.acc;
|
|
177
|
+
if (acc.dmPolicy === "none") return;
|
|
178
|
+
if (acc.dmPolicy === "open") {
|
|
179
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (acc.dmPolicy === "allowlist") {
|
|
183
|
+
if (!acc.allowFrom.includes(userId)) {
|
|
184
|
+
console.log(chalk.default.gray(` mattermost[${acc.id}]: drop DM from ${userId} (dmPolicy=allowlist)`));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (acc.dmPolicy === "pairing") {
|
|
191
|
+
if (acc.approvedPairings.includes(userId)) {
|
|
192
|
+
this._emit(userId, channelId, text, senderName, postId, true);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const upper = text.trim().toUpperCase();
|
|
196
|
+
if (acc.pendingPairings[upper]) {
|
|
197
|
+
acc.approvedPairings.push(userId);
|
|
198
|
+
delete acc.pendingPairings[upper];
|
|
199
|
+
await this._saveState();
|
|
200
|
+
await this.sendMessage(channelId, "🦅 Paired!");
|
|
201
|
+
this.emit("pairing:approved", {
|
|
202
|
+
accountId: acc.id,
|
|
203
|
+
userId,
|
|
204
|
+
channelId
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
|
|
209
|
+
acc.pendingPairings[code] = userId;
|
|
210
|
+
await this._saveState();
|
|
211
|
+
await this.sendMessage(channelId, `🦅 Pairing code: \`${code}\`\nApprove: hyperclaw pairing approve mattermost ${code}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
_routeChannel(userId, channelId, text, senderName, postId) {
|
|
215
|
+
const acc = this.acc;
|
|
216
|
+
if (acc.groupPolicy === "allowlist") {
|
|
217
|
+
const combined = [...acc.groupAllowFrom, ...acc.allowFrom];
|
|
218
|
+
if (combined.length > 0) {
|
|
219
|
+
const match = combined.some((p) => {
|
|
220
|
+
if (p === "*") return true;
|
|
221
|
+
if (acc.dangerouslyAllowNameMatching) {
|
|
222
|
+
const name = senderName.replace(/^@/, "");
|
|
223
|
+
return name === p || userId === p;
|
|
224
|
+
}
|
|
225
|
+
return userId === p;
|
|
226
|
+
});
|
|
227
|
+
if (!match) {
|
|
228
|
+
console.log(chalk.default.gray(` mattermost[${acc.id}]: drop group sender ${userId} (policy=allowlist)`));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const botMentionPatterns = [
|
|
234
|
+
`@${this.botUserId}`,
|
|
235
|
+
`@hyperclaw`,
|
|
236
|
+
`@${acc.name?.toLowerCase()}`
|
|
237
|
+
];
|
|
238
|
+
const isMentioned = botMentionPatterns.some((p) => text.toLowerCase().includes(p.toLowerCase()));
|
|
239
|
+
if (acc.chatmode === "oncall" || acc.chatmode !== "onmessage" && acc.requireMention) {
|
|
240
|
+
if (!isMentioned) {
|
|
241
|
+
console.log(chalk.default.gray(` mattermost[${acc.id}]: drop channel ${channelId} (missing-mention, chatmode=oncall)`));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
} else if (acc.chatmode === "onchar") {
|
|
245
|
+
const hasPrefix = acc.oncharPrefixes.some((p) => text.startsWith(p));
|
|
246
|
+
if (!hasPrefix && !isMentioned) {
|
|
247
|
+
console.log(chalk.default.gray(` mattermost[${acc.id}]: drop channel ${channelId} (no prefix/mention, chatmode=onchar)`));
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
this._emit(userId, channelId, text, senderName, postId, false);
|
|
252
|
+
}
|
|
253
|
+
_emit(from, chatId, text, senderName, postId, isDM) {
|
|
254
|
+
this.emit("message", {
|
|
255
|
+
accountId: this.acc.id,
|
|
256
|
+
id: postId,
|
|
257
|
+
from,
|
|
258
|
+
chatId,
|
|
259
|
+
text,
|
|
260
|
+
senderName,
|
|
261
|
+
isDM,
|
|
262
|
+
channelId: "mattermost"
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
async handleWebhook(body, webhookToken) {
|
|
266
|
+
let params = {};
|
|
267
|
+
const trimmed = (body || "").trim();
|
|
268
|
+
if (trimmed.startsWith("{")) try {
|
|
269
|
+
params = JSON.parse(trimmed);
|
|
270
|
+
} catch {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
else for (const pair of body.split("&")) {
|
|
274
|
+
const eq = pair.indexOf("=");
|
|
275
|
+
const k = eq >= 0 ? decodeURIComponent(pair.slice(0, eq).replace(/\+/g, " ")) : decodeURIComponent(pair.replace(/\+/g, " "));
|
|
276
|
+
const v = eq >= 0 ? decodeURIComponent((pair.slice(eq + 1) || "").replace(/\+/g, " ")) : "";
|
|
277
|
+
if (k) params[k] = v;
|
|
278
|
+
}
|
|
279
|
+
if (params.token !== webhookToken) {
|
|
280
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${this.acc.id}]: invalid webhook token`));
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const channelId = params.channel_id;
|
|
284
|
+
const userId = params.user_id;
|
|
285
|
+
const senderName = params.user_name || "";
|
|
286
|
+
let text = (params.text || "").trim();
|
|
287
|
+
const triggerWord = params.trigger_word || "";
|
|
288
|
+
if (triggerWord && text.startsWith(triggerWord)) text = text.slice(triggerWord.length).trim();
|
|
289
|
+
if (!channelId || !userId || !text) return;
|
|
290
|
+
this._routeChannel(userId, channelId, text, senderName, params.post_id || `${channelId}-${Date.now()}`);
|
|
291
|
+
}
|
|
292
|
+
async handleSlashCommand(payload, expectedToken) {
|
|
293
|
+
if (payload.token !== expectedToken) {
|
|
294
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${this.acc.id}]: slash command token mismatch`));
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
const text = (payload.text || "").trim();
|
|
298
|
+
const userId = payload.user_id || "";
|
|
299
|
+
const channelId = payload.channel_id || "";
|
|
300
|
+
const commandName = payload.command || "";
|
|
301
|
+
this.emit("slash_command", {
|
|
302
|
+
accountId: this.acc.id,
|
|
303
|
+
command: commandName,
|
|
304
|
+
text,
|
|
305
|
+
userId,
|
|
306
|
+
channelId,
|
|
307
|
+
senderName: payload.user_name || "",
|
|
308
|
+
responseUrl: payload.response_url || ""
|
|
309
|
+
});
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
/** Register all native slash commands via Mattermost REST API. */
|
|
313
|
+
async registerSlashCommands(teamId, commands) {
|
|
314
|
+
const acc = this.acc;
|
|
315
|
+
if (!acc.commands.native || acc.commands.native === "auto") return;
|
|
316
|
+
const callbackUrl = acc.commands.callbackUrl || `http://localhost:18789${acc.commands.callbackPath ?? "/api/channels/mattermost/command"}`;
|
|
317
|
+
for (const cmd of commands) try {
|
|
318
|
+
await mmApi(acc.baseUrl, acc.botToken, "POST", "/api/v4/commands", {
|
|
319
|
+
team_id: teamId,
|
|
320
|
+
trigger: cmd.trigger.replace(/^\//, ""),
|
|
321
|
+
method: "P",
|
|
322
|
+
title: cmd.description,
|
|
323
|
+
description: cmd.description,
|
|
324
|
+
url: callbackUrl,
|
|
325
|
+
username: acc.name ?? "hyperclaw-bot",
|
|
326
|
+
auto_complete: true,
|
|
327
|
+
auto_complete_hint: "[prompt]",
|
|
328
|
+
auto_complete_desc: cmd.description
|
|
329
|
+
});
|
|
330
|
+
console.log(chalk.default.gray(` mattermost[${acc.id}]: registered /${cmd.trigger}`));
|
|
331
|
+
} catch (e) {
|
|
332
|
+
console.log(chalk.default.yellow(` ⚠ mattermost[${acc.id}]: failed to register /${cmd.trigger}: ${e.message}`));
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
handleInteraction(context) {
|
|
336
|
+
const secret = deriveInteractionSecret(this.acc.botToken);
|
|
337
|
+
if (!verifyInteraction(context, secret)) return {
|
|
338
|
+
ok: false,
|
|
339
|
+
error: "invalid _token"
|
|
340
|
+
};
|
|
341
|
+
if (!context["action_id"]) return {
|
|
342
|
+
ok: false,
|
|
343
|
+
error: "missing action_id in context"
|
|
344
|
+
};
|
|
345
|
+
this.emit("interaction", {
|
|
346
|
+
accountId: this.acc.id,
|
|
347
|
+
context
|
|
348
|
+
});
|
|
349
|
+
return { ok: true };
|
|
350
|
+
}
|
|
351
|
+
async addReaction(postId, emoji) {
|
|
352
|
+
if (!this.acc.actions.reactions) return;
|
|
353
|
+
const name = emoji.replace(/:/g, "");
|
|
354
|
+
await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/reactions", {
|
|
355
|
+
user_id: this.botUserId,
|
|
356
|
+
post_id: postId,
|
|
357
|
+
emoji_name: name
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
async removeReaction(postId, emoji) {
|
|
361
|
+
if (!this.acc.actions.reactions) return;
|
|
362
|
+
const name = emoji.replace(/:/g, "");
|
|
363
|
+
await mmApi(this.acc.baseUrl, this.acc.botToken, "DELETE", `/api/v4/users/${this.botUserId}/posts/${postId}/reactions/${name}`);
|
|
364
|
+
}
|
|
365
|
+
async sendMessage(channelId, text, attachments) {
|
|
366
|
+
const chunks = text.match(/.{1,4000}/gs) || [text];
|
|
367
|
+
let lastPost;
|
|
368
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
369
|
+
const body = {
|
|
370
|
+
channel_id: channelId,
|
|
371
|
+
message: chunks[i].slice(0, 16383)
|
|
372
|
+
};
|
|
373
|
+
if (i === chunks.length - 1 && attachments?.length) body.props = { attachments };
|
|
374
|
+
lastPost = await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/posts", body);
|
|
375
|
+
}
|
|
376
|
+
return lastPost;
|
|
377
|
+
}
|
|
378
|
+
async resolveTarget(target) {
|
|
379
|
+
if (target.startsWith("channel:")) return {
|
|
380
|
+
type: "channel",
|
|
381
|
+
id: target.slice(8)
|
|
382
|
+
};
|
|
383
|
+
if (target.startsWith("user:")) {
|
|
384
|
+
const ch = await this._getDmChannel(target.slice(5));
|
|
385
|
+
return {
|
|
386
|
+
type: "dm",
|
|
387
|
+
id: ch
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
if (target.startsWith("@")) {
|
|
391
|
+
const users = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", `/api/v4/users?in_team=&per_page=200&page=0`);
|
|
392
|
+
const username = target.slice(1).toLowerCase();
|
|
393
|
+
const found = Array.isArray(users) ? users.find((u) => u.username?.toLowerCase() === username) : null;
|
|
394
|
+
if (!found) throw new Error(`Mattermost: user ${target} not found`);
|
|
395
|
+
const ch = await this._getDmChannel(found.id);
|
|
396
|
+
return {
|
|
397
|
+
type: "dm",
|
|
398
|
+
id: ch
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
if (target.startsWith("#")) {
|
|
402
|
+
const name = target.slice(1);
|
|
403
|
+
const ch = await mmApi(this.acc.baseUrl, this.acc.botToken, "GET", `/api/v4/channels/name/${name}`);
|
|
404
|
+
return {
|
|
405
|
+
type: "channel",
|
|
406
|
+
id: ch.id
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
return {
|
|
410
|
+
type: "channel",
|
|
411
|
+
id: target
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
async _getDmChannel(userId) {
|
|
415
|
+
const ch = await mmApi(this.acc.baseUrl, this.acc.botToken, "POST", "/api/v4/channels/direct", [this.botUserId, userId]);
|
|
416
|
+
return ch.id;
|
|
417
|
+
}
|
|
418
|
+
approvePairing(code) {
|
|
419
|
+
const upper = code.toUpperCase();
|
|
420
|
+
if (!this.acc.pendingPairings[upper]) return false;
|
|
421
|
+
this.acc.approvedPairings.push(this.acc.pendingPairings[upper]);
|
|
422
|
+
delete this.acc.pendingPairings[upper];
|
|
423
|
+
this._saveState();
|
|
424
|
+
return true;
|
|
425
|
+
}
|
|
426
|
+
listPendingPairings() {
|
|
427
|
+
return { ...this.acc.pendingPairings };
|
|
428
|
+
}
|
|
429
|
+
async _saveState() {
|
|
430
|
+
await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
|
|
431
|
+
let state = {};
|
|
432
|
+
try {
|
|
433
|
+
state = await fs_extra.default.readJson(STATE_FILE);
|
|
434
|
+
} catch {}
|
|
435
|
+
state[this.acc.id] = {
|
|
436
|
+
approvedPairings: this.acc.approvedPairings,
|
|
437
|
+
pendingPairings: this.acc.pendingPairings
|
|
438
|
+
};
|
|
439
|
+
await fs_extra.default.writeJson(STATE_FILE, state, { spaces: 2 });
|
|
440
|
+
}
|
|
441
|
+
async loadState() {
|
|
442
|
+
try {
|
|
443
|
+
const state = await fs_extra.default.readJson(STATE_FILE);
|
|
444
|
+
const s = state[this.acc.id];
|
|
445
|
+
if (s?.approvedPairings) this.acc.approvedPairings = s.approvedPairings;
|
|
446
|
+
if (s?.pendingPairings) this.acc.pendingPairings = s.pendingPairings;
|
|
447
|
+
} catch {}
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
var MattermostConnector = class extends events.EventEmitter {
|
|
451
|
+
accounts = /* @__PURE__ */ new Map();
|
|
452
|
+
rawConfig;
|
|
453
|
+
constructor(config) {
|
|
454
|
+
super();
|
|
455
|
+
this.rawConfig = config;
|
|
456
|
+
}
|
|
457
|
+
async connect() {
|
|
458
|
+
const cfg = this.rawConfig;
|
|
459
|
+
const accountDefs = cfg.accounts ?? { default: cfg };
|
|
460
|
+
for (const [id, rawAcc] of Object.entries(accountDefs)) {
|
|
461
|
+
const merged = {
|
|
462
|
+
...cfg,
|
|
463
|
+
...rawAcc
|
|
464
|
+
};
|
|
465
|
+
const state = {
|
|
466
|
+
approved: cfg.approvedPairings ?? [],
|
|
467
|
+
pending: cfg.pendingPairings ?? {}
|
|
468
|
+
};
|
|
469
|
+
const acc = resolveAccount(id, merged, state);
|
|
470
|
+
if (!acc.botToken || !acc.baseUrl) {
|
|
471
|
+
console.log(chalk.default.yellow(` ⚠ Mattermost[${id}]: missing botToken or baseUrl — skipping`));
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const conn = new SingleAccountConnector(acc);
|
|
475
|
+
await conn.loadState();
|
|
476
|
+
conn.on("message", (msg) => this.emit("message", msg));
|
|
477
|
+
conn.on("connected", (info) => this.emit("connected", info));
|
|
478
|
+
conn.on("pairing:approved", (info) => this.emit("pairing:approved", info));
|
|
479
|
+
conn.on("interaction", (info) => this.emit("interaction", info));
|
|
480
|
+
conn.on("reaction", (info) => this.emit("reaction", info));
|
|
481
|
+
conn.on("slash_command", (info) => this.emit("slash_command", info));
|
|
482
|
+
await conn.connect();
|
|
483
|
+
this.accounts.set(id, conn);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
disconnect() {
|
|
487
|
+
for (const conn of this.accounts.values()) conn.disconnect();
|
|
488
|
+
this.accounts.clear();
|
|
489
|
+
}
|
|
490
|
+
_acc(accountId = "default") {
|
|
491
|
+
const conn = this.accounts.get(accountId);
|
|
492
|
+
if (!conn) throw new Error(`Mattermost: account '${accountId}' not found`);
|
|
493
|
+
return conn;
|
|
494
|
+
}
|
|
495
|
+
async sendMessage(channelId, text, attachments, accountId) {
|
|
496
|
+
return this._acc(accountId).sendMessage(channelId, text, attachments);
|
|
497
|
+
}
|
|
498
|
+
async addReaction(postId, emoji, accountId) {
|
|
499
|
+
return this._acc(accountId).addReaction(postId, emoji);
|
|
500
|
+
}
|
|
501
|
+
async removeReaction(postId, emoji, accountId) {
|
|
502
|
+
return this._acc(accountId).removeReaction(postId, emoji);
|
|
503
|
+
}
|
|
504
|
+
async resolveTarget(target, accountId) {
|
|
505
|
+
return this._acc(accountId).resolveTarget(target);
|
|
506
|
+
}
|
|
507
|
+
handleInteraction(context, accountId) {
|
|
508
|
+
return this._acc(accountId).handleInteraction(context);
|
|
509
|
+
}
|
|
510
|
+
async handleWebhook(body, webhookToken, accountId) {
|
|
511
|
+
return this._acc(accountId).handleWebhook(body, webhookToken);
|
|
512
|
+
}
|
|
513
|
+
async handleSlashCommand(payload, expectedToken, accountId) {
|
|
514
|
+
return this._acc(accountId).handleSlashCommand(payload, expectedToken);
|
|
515
|
+
}
|
|
516
|
+
approvePairing(code, accountId) {
|
|
517
|
+
return this._acc(accountId).approvePairing(code);
|
|
518
|
+
}
|
|
519
|
+
listPendingPairings(accountId) {
|
|
520
|
+
return this._acc(accountId).listPendingPairings();
|
|
521
|
+
}
|
|
522
|
+
getAccountIds() {
|
|
523
|
+
return Array.from(this.accounts.keys());
|
|
524
|
+
}
|
|
525
|
+
isRunning() {
|
|
526
|
+
return this.accounts.size > 0;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
//#endregion
|
|
531
|
+
exports.MattermostConnector = MattermostConnector;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-jS-bbMI5.js');
|
|
2
|
+
const chalk = require_chunk.__toESM(require("chalk"));
|
|
3
|
+
const fs_extra = require_chunk.__toESM(require("fs-extra"));
|
|
4
|
+
const path = require_chunk.__toESM(require("path"));
|
|
5
|
+
const os = require_chunk.__toESM(require("os"));
|
|
6
|
+
const crypto = require_chunk.__toESM(require("crypto"));
|
|
7
|
+
const https = require_chunk.__toESM(require("https"));
|
|
8
|
+
const events = require_chunk.__toESM(require("events"));
|
|
9
|
+
|
|
10
|
+
//#region extensions/viber/src/connector.ts
|
|
11
|
+
const STATE_FILE = path.default.join(os.default.homedir(), ".hyperclaw", "viber-state.json");
|
|
12
|
+
function viberReq(token, endpoint, body) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
const payload = JSON.stringify(body);
|
|
15
|
+
const req = https.default.request({
|
|
16
|
+
hostname: "chatapi.viber.com",
|
|
17
|
+
port: 443,
|
|
18
|
+
path: `/pa${endpoint}`,
|
|
19
|
+
method: "POST",
|
|
20
|
+
headers: {
|
|
21
|
+
"X-Viber-Auth-Token": token,
|
|
22
|
+
"Content-Type": "application/json",
|
|
23
|
+
"Content-Length": Buffer.byteLength(payload)
|
|
24
|
+
}
|
|
25
|
+
}, (res) => {
|
|
26
|
+
let data = "";
|
|
27
|
+
res.on("data", (c) => data += c);
|
|
28
|
+
res.on("end", () => {
|
|
29
|
+
try {
|
|
30
|
+
const r = JSON.parse(data);
|
|
31
|
+
if (r.status !== 0) reject(new Error(r.status_message));
|
|
32
|
+
else resolve(r);
|
|
33
|
+
} catch {
|
|
34
|
+
reject(new Error("Invalid JSON"));
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
req.on("error", reject);
|
|
39
|
+
req.write(payload);
|
|
40
|
+
req.end();
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
var ViberConnector = class extends events.EventEmitter {
|
|
44
|
+
config;
|
|
45
|
+
running = false;
|
|
46
|
+
constructor(config) {
|
|
47
|
+
super();
|
|
48
|
+
this.config = {
|
|
49
|
+
dmPolicy: "allowlist",
|
|
50
|
+
allowFrom: [],
|
|
51
|
+
approvedPairings: [],
|
|
52
|
+
pendingPairings: {},
|
|
53
|
+
...config
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
async connect() {
|
|
57
|
+
await viberReq(this.config.authToken, "/set_webhook", {
|
|
58
|
+
url: this.config.webhookUrl,
|
|
59
|
+
event_types: [
|
|
60
|
+
"delivered",
|
|
61
|
+
"seen",
|
|
62
|
+
"failed",
|
|
63
|
+
"subscribed",
|
|
64
|
+
"unsubscribed",
|
|
65
|
+
"conversation_started"
|
|
66
|
+
],
|
|
67
|
+
send_name: true
|
|
68
|
+
});
|
|
69
|
+
const info = await viberReq(this.config.authToken, "/get_account_info", {});
|
|
70
|
+
await this.loadState();
|
|
71
|
+
this.running = true;
|
|
72
|
+
console.log(chalk.default.green(` 🦅 Viber: ${info.name || this.config.botName} connected`));
|
|
73
|
+
this.emit("connected", { name: info.name });
|
|
74
|
+
}
|
|
75
|
+
disconnect() {
|
|
76
|
+
this.running = false;
|
|
77
|
+
}
|
|
78
|
+
verifySignature(body, signature) {
|
|
79
|
+
const expected = crypto.default.createHmac("sha256", this.config.authToken).update(body).digest("hex");
|
|
80
|
+
try {
|
|
81
|
+
return crypto.default.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async handleWebhook(body, signature) {
|
|
87
|
+
if (signature && !this.verifySignature(body, signature)) {
|
|
88
|
+
console.log(chalk.default.yellow(" ⚠ Viber: invalid signature"));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
let payload;
|
|
92
|
+
try {
|
|
93
|
+
payload = JSON.parse(body);
|
|
94
|
+
} catch {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (payload.event === "message") {
|
|
98
|
+
const userId = payload.sender?.id;
|
|
99
|
+
const text = payload.message?.text;
|
|
100
|
+
if (!userId || !text) return;
|
|
101
|
+
const allowed = await this.checkDMPolicy(userId, text);
|
|
102
|
+
if (!allowed) return;
|
|
103
|
+
this.emit("message", {
|
|
104
|
+
id: payload.message_token?.toString(),
|
|
105
|
+
channelId: "viber",
|
|
106
|
+
from: userId,
|
|
107
|
+
chatId: userId,
|
|
108
|
+
text,
|
|
109
|
+
senderName: payload.sender?.name,
|
|
110
|
+
timestamp: new Date(payload.timestamp).toISOString(),
|
|
111
|
+
isDM: true
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (payload.event === "conversation_started") await this.sendMessage(payload.user?.id, `🦅 Hi ${payload.user?.name || "there"}! I'm HyperClaw.`);
|
|
115
|
+
}
|
|
116
|
+
async checkDMPolicy(from, text) {
|
|
117
|
+
if (this.config.dmPolicy === "none") return false;
|
|
118
|
+
if (this.config.dmPolicy === "open") return true;
|
|
119
|
+
if (this.config.dmPolicy === "allowlist") {
|
|
120
|
+
if (this.config.allowFrom.includes(from)) return true;
|
|
121
|
+
await this.sendMessage(from, "🦅 HyperClaw: Not on allowlist.");
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
if (this.config.dmPolicy === "pairing") {
|
|
125
|
+
if (this.config.approvedPairings.includes(from)) return true;
|
|
126
|
+
const upper = text.trim().toUpperCase();
|
|
127
|
+
if (this.config.pendingPairings[upper]) {
|
|
128
|
+
this.config.approvedPairings.push(from);
|
|
129
|
+
delete this.config.pendingPairings[upper];
|
|
130
|
+
await this.saveState();
|
|
131
|
+
await this.sendMessage(from, "🦅 Paired!");
|
|
132
|
+
this.emit("pairing:approved", {
|
|
133
|
+
userId: from,
|
|
134
|
+
channelId: "viber"
|
|
135
|
+
});
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
const code = Array.from({ length: 6 }, () => "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[Math.floor(Math.random() * 32)]).join("");
|
|
139
|
+
this.config.pendingPairings[code] = from;
|
|
140
|
+
await this.saveState();
|
|
141
|
+
await this.sendMessage(from, `🦅 Pairing code: ${code}\nApprove: hyperclaw pairing approve viber ${code}`);
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
async sendMessage(userId, text) {
|
|
147
|
+
await viberReq(this.config.authToken, "/send_message", {
|
|
148
|
+
receiver: userId,
|
|
149
|
+
type: "text",
|
|
150
|
+
sender: { name: this.config.botName },
|
|
151
|
+
text: text.slice(0, 7e3)
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
approvePairing(code) {
|
|
155
|
+
const upper = code.toUpperCase();
|
|
156
|
+
if (!this.config.pendingPairings[upper]) return false;
|
|
157
|
+
this.config.approvedPairings.push(this.config.pendingPairings[upper]);
|
|
158
|
+
delete this.config.pendingPairings[upper];
|
|
159
|
+
this.saveState();
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
async loadState() {
|
|
163
|
+
try {
|
|
164
|
+
const s = await fs_extra.default.readJson(STATE_FILE);
|
|
165
|
+
if (s.p) this.config.pendingPairings = s.p;
|
|
166
|
+
if (s.a) this.config.approvedPairings = s.a;
|
|
167
|
+
} catch {}
|
|
168
|
+
}
|
|
169
|
+
async saveState() {
|
|
170
|
+
await fs_extra.default.ensureDir(path.default.dirname(STATE_FILE));
|
|
171
|
+
await fs_extra.default.writeJson(STATE_FILE, {
|
|
172
|
+
p: this.config.pendingPairings,
|
|
173
|
+
a: this.config.approvedPairings
|
|
174
|
+
}, { spaces: 2 });
|
|
175
|
+
}
|
|
176
|
+
isRunning() {
|
|
177
|
+
return this.running;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
//#endregion
|
|
182
|
+
exports.ViberConnector = ViberConnector;
|