@coffeerunhobby/mcp-ha-connect 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -3
- package/dist/config.d.ts +4 -0
- package/dist/config.js +6 -0
- package/dist/config.js.map +1 -1
- package/dist/haClient/automations.d.ts +18 -2
- package/dist/haClient/automations.js +25 -7
- package/dist/haClient/automations.js.map +1 -1
- package/dist/haClient/events.d.ts +60 -7
- package/dist/haClient/events.js +252 -47
- package/dist/haClient/events.js.map +1 -1
- package/dist/haClient/index.d.ts +2 -1
- package/dist/haClient/index.js +4 -3
- package/dist/haClient/index.js.map +1 -1
- package/dist/haClient/wsCommand.d.ts +16 -0
- package/dist/haClient/wsCommand.js +36 -0
- package/dist/haClient/wsCommand.js.map +1 -0
- package/dist/omadaClient/site.js +15 -2
- package/dist/omadaClient/site.js.map +1 -1
- package/dist/ownerQuestions/service.d.ts +167 -0
- package/dist/ownerQuestions/service.js +439 -0
- package/dist/ownerQuestions/service.js.map +1 -0
- package/dist/server/common.d.ts +3 -0
- package/dist/server/common.js +2 -1
- package/dist/server/common.js.map +1 -1
- package/dist/server/http.js +30 -6
- package/dist/server/http.js.map +1 -1
- package/dist/server/stream.d.ts +2 -0
- package/dist/server/stream.js +2 -1
- package/dist/server/stream.js.map +1 -1
- package/dist/tools/common.d.ts +1 -1
- package/dist/tools/common.js +4 -1
- package/dist/tools/common.js.map +1 -1
- package/dist/tools/homeassistant/askOwner.d.ts +29 -0
- package/dist/tools/homeassistant/askOwner.js +85 -0
- package/dist/tools/homeassistant/askOwner.js.map +1 -0
- package/dist/tools/homeassistant/getAutomationTrace.d.ts +5 -0
- package/dist/tools/homeassistant/getAutomationTrace.js +10 -5
- package/dist/tools/homeassistant/getAutomationTrace.js.map +1 -1
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +5 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/utils/plainText.d.ts +22 -0
- package/dist/utils/plainText.js +39 -0
- package/dist/utils/plainText.js.map +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/CHANGELOG.md +19 -0
- package/openapi.json +1 -1
- package/package.json +1 -1
- package/src/config.ts +10 -0
- package/src/haClient/automations.ts +39 -7
- package/src/haClient/events.ts +289 -56
- package/src/haClient/index.ts +10 -4
- package/src/haClient/wsCommand.ts +44 -0
- package/src/omadaClient/site.ts +17 -2
- package/src/ownerQuestions/service.ts +536 -0
- package/src/server/common.ts +5 -1
- package/src/server/http.ts +30 -6
- package/src/server/stream.ts +4 -1
- package/src/tools/common.ts +4 -1
- package/src/tools/homeassistant/askOwner.ts +133 -0
- package/src/tools/homeassistant/getAutomationTrace.ts +13 -7
- package/src/tools/index.ts +8 -1
- package/src/utils/plainText.ts +48 -0
- package/src/version.ts +1 -1
- package/tests/config.test.ts +12 -0
- package/tests/haClient/automationTrace.test.ts +59 -0
- package/tests/haClient/automations.test.ts +16 -0
- package/tests/haClient/events.test.ts +455 -0
- package/tests/haClient/eventsTls.test.ts +52 -0
- package/tests/omadaClient/ntp.test.ts +15 -0
- package/tests/ownerQuestions/service.test.ts +499 -0
- package/tests/ownerQuestions/tools.test.ts +186 -0
- package/tests/tools/homeassistant/handlers.test.ts +10 -1
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner questions: ask the owner a yes/no-style question as an actionable phone
|
|
3
|
+
* notification and collect the button they tap.
|
|
4
|
+
*
|
|
5
|
+
* Stateless by design: everything needed to recognise a question travels in
|
|
6
|
+
* signed identifiers, so a server restart does not lose open questions.
|
|
7
|
+
* - The requestId given to the caller carries the question, title, buttons,
|
|
8
|
+
* target, expiry, the asking token's `sub` and a random nonce, signed with a
|
|
9
|
+
* key derived from the server secret.
|
|
10
|
+
* - Each button's action id carries the nonce, the button index, the expiry,
|
|
11
|
+
* the target and its own signature, so a tap that arrives after a restart is
|
|
12
|
+
* still verified and attributed. The secret never leaves the server, and the
|
|
13
|
+
* requestId is not enough to forge a button id.
|
|
14
|
+
* Only answers (and cancellations) are kept in memory until they are read. A tap
|
|
15
|
+
* that lands while the server is down is lost; the question then expires as NO.
|
|
16
|
+
*
|
|
17
|
+
* A tap counts only if Home Assistant reports it as coming from a mobile app
|
|
18
|
+
* webhook (origin REMOTE, with a user), so an automation that fires a fake
|
|
19
|
+
* `mobile_app_notification_action` event (origin LOCAL) cannot approve anything.
|
|
20
|
+
* With `allowedUserIds` (MCP_OWNER_QUESTIONS_HA_USERS) only those HA users can answer.
|
|
21
|
+
*
|
|
22
|
+
* Known limit, accepted: cancellations and answers are remembered in memory
|
|
23
|
+
* only, while a button's signed id stays valid until the question expires. After
|
|
24
|
+
* a restart, re-sending an old button id through Home Assistant's own API (which
|
|
25
|
+
* needs an HA login, and the id from HA's history) could answer a question that
|
|
26
|
+
* had been cancelled or denied. The phone itself no longer shows the buttons.
|
|
27
|
+
* Anyone with that access can already control the house directly.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
31
|
+
|
|
32
|
+
import { logger } from '../utils/logger.js';
|
|
33
|
+
|
|
34
|
+
export const ACTION_EVENT = 'mobile_app_notification_action';
|
|
35
|
+
|
|
36
|
+
export const LIMITS = {
|
|
37
|
+
questionChars: 256,
|
|
38
|
+
titleChars: 60,
|
|
39
|
+
buttonChars: 20,
|
|
40
|
+
maxButtons: 3,
|
|
41
|
+
minTimeoutSeconds: 60,
|
|
42
|
+
maxTimeoutSeconds: 7 * 24 * 60 * 60,
|
|
43
|
+
defaultTimeoutSeconds: 600,
|
|
44
|
+
maxWaitSeconds: 50,
|
|
45
|
+
maxOpenPerCaller: 3,
|
|
46
|
+
maxPerCallerPerHour: 30,
|
|
47
|
+
} as const;
|
|
48
|
+
|
|
49
|
+
const REQUEST_PREFIX = 'q1';
|
|
50
|
+
const ACTION_PREFIX = 'MCPASK';
|
|
51
|
+
/** How long the confirmation that replaces an answered question stays on the phone. */
|
|
52
|
+
const CONFIRMATION_SECONDS = 300;
|
|
53
|
+
/** Outcomes stay readable this long after their question expired. */
|
|
54
|
+
const OUTCOME_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
55
|
+
const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
|
|
56
|
+
|
|
57
|
+
export interface AskOwnerInput {
|
|
58
|
+
question: string;
|
|
59
|
+
title: string;
|
|
60
|
+
buttons: string[];
|
|
61
|
+
target: string;
|
|
62
|
+
timeoutSeconds: number;
|
|
63
|
+
channel?: string;
|
|
64
|
+
importance?: 'high' | 'default' | 'low' | 'min';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type OwnerAnswer =
|
|
68
|
+
| {
|
|
69
|
+
status: 'answered';
|
|
70
|
+
index: number;
|
|
71
|
+
button: string;
|
|
72
|
+
answeredAt: string;
|
|
73
|
+
answeredBy: string;
|
|
74
|
+
question: string;
|
|
75
|
+
buttons: string[];
|
|
76
|
+
}
|
|
77
|
+
| { status: 'pending'; expiresAt: string; question: string; buttons: string[] }
|
|
78
|
+
| { status: 'timeout'; expiredAt: string; question: string; buttons: string[] }
|
|
79
|
+
| { status: 'cancelled'; cancelledAt: string; question: string; buttons: string[] }
|
|
80
|
+
| { status: 'unknown'; reason: string };
|
|
81
|
+
|
|
82
|
+
/** Signed contents of a requestId. */
|
|
83
|
+
interface QuestionPayload {
|
|
84
|
+
v: 1;
|
|
85
|
+
n: string;
|
|
86
|
+
s: string;
|
|
87
|
+
t: string;
|
|
88
|
+
e: number;
|
|
89
|
+
b: string[];
|
|
90
|
+
q: string;
|
|
91
|
+
ti: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
type Outcome =
|
|
95
|
+
| { status: 'answered'; index: number; answeredAt: number; answeredBy: string }
|
|
96
|
+
| { status: 'cancelled'; cancelledAt: number };
|
|
97
|
+
|
|
98
|
+
export interface OwnerQuestionDeps {
|
|
99
|
+
/** Calls `notify.<target>`. */
|
|
100
|
+
notify: (target: string, serviceData: Record<string, unknown>) => Promise<unknown>;
|
|
101
|
+
/**
|
|
102
|
+
* Subscribes to a Home Assistant event type. Rejects if Home Assistant refuses
|
|
103
|
+
* it now; `onRejected` reports a refusal seen later (e.g. after a reconnect).
|
|
104
|
+
*/
|
|
105
|
+
subscribe: (
|
|
106
|
+
eventType: string,
|
|
107
|
+
callback: (event: ActionEvent) => void,
|
|
108
|
+
onRejected: (error: Error) => void
|
|
109
|
+
) => Promise<unknown>;
|
|
110
|
+
/** Key material for signing (the server's auth secret); a random key is used when absent. */
|
|
111
|
+
secret?: string;
|
|
112
|
+
/** HA user ids allowed to answer; empty or absent = any HA user. */
|
|
113
|
+
allowedUserIds?: string[];
|
|
114
|
+
now?: () => number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface ActionEvent {
|
|
118
|
+
event_type: string;
|
|
119
|
+
data: { action?: unknown; [key: string]: unknown };
|
|
120
|
+
origin: string;
|
|
121
|
+
time_fired?: string;
|
|
122
|
+
context: { user_id: string | null };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const b64url = (buffer: Buffer): string => buffer.toString('base64url');
|
|
126
|
+
|
|
127
|
+
export class OwnerQuestionService {
|
|
128
|
+
private readonly key: Buffer;
|
|
129
|
+
private readonly now: () => number;
|
|
130
|
+
/** Final outcomes by nonce, until the question's expiry passes. */
|
|
131
|
+
private readonly outcomes = new Map<string, Outcome & { expiresAt: number }>();
|
|
132
|
+
/** Open questions per caller sub: nonce -> expiry (ms). */
|
|
133
|
+
private readonly open = new Map<string, Map<string, number>>();
|
|
134
|
+
/** Ask timestamps per caller sub, for the hourly cap. */
|
|
135
|
+
private readonly asked = new Map<string, number[]>();
|
|
136
|
+
/** Pollers waiting for an outcome, by nonce. */
|
|
137
|
+
private readonly waiters = new Map<string, Set<() => void>>();
|
|
138
|
+
/** Expiry timers by nonce (best effort: lost on restart; the phone also times out on its own). */
|
|
139
|
+
private readonly expiryTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
140
|
+
/** Labels and target of open questions, for nicer confirmations while the server stays up. */
|
|
141
|
+
private readonly known = new Map<string, { target: string; title: string; buttons: string[]; expiresAt: number }>();
|
|
142
|
+
private sweepTimer: ReturnType<typeof setInterval> | undefined;
|
|
143
|
+
/** Why questions cannot be answered right now (Home Assistant refused the tap subscription). */
|
|
144
|
+
private unavailable: string | undefined;
|
|
145
|
+
|
|
146
|
+
constructor(private readonly deps: OwnerQuestionDeps) {
|
|
147
|
+
this.now = deps.now ?? Date.now;
|
|
148
|
+
if (deps.secret) {
|
|
149
|
+
this.key = createHmac('sha256', deps.secret).update('mcp-ha-connect/owner-questions/v1').digest();
|
|
150
|
+
} else {
|
|
151
|
+
this.key = randomBytes(32);
|
|
152
|
+
logger.warn('Owner questions: no server secret configured; open questions will not survive a restart');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async start(): Promise<void> {
|
|
157
|
+
await this.deps.subscribe(
|
|
158
|
+
ACTION_EVENT,
|
|
159
|
+
(event) => this.handleActionEvent(event),
|
|
160
|
+
() => {
|
|
161
|
+
this.unavailable =
|
|
162
|
+
'Home Assistant refused the subscription to notification taps (the server needs an admin Home Assistant token)';
|
|
163
|
+
logger.error(`Owner questions unavailable: ${this.unavailable}`);
|
|
164
|
+
}
|
|
165
|
+
);
|
|
166
|
+
this.sweepTimer = setInterval(() => this.sweep(), SWEEP_INTERVAL_MS);
|
|
167
|
+
this.sweepTimer.unref?.();
|
|
168
|
+
logger.info('Owner questions: listening for notification taps');
|
|
169
|
+
if (!this.deps.allowedUserIds?.length) {
|
|
170
|
+
logger.warn('Owner questions: any Home Assistant user can answer; set MCP_OWNER_QUESTIONS_HA_USERS to restrict it');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
stop(): void {
|
|
175
|
+
clearInterval(this.sweepTimer);
|
|
176
|
+
for (const timer of this.expiryTimers.values()) clearTimeout(timer);
|
|
177
|
+
this.expiryTimers.clear();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async ask(input: AskOwnerInput, caller: string): Promise<{ requestId: string; expiresAt: string }> {
|
|
181
|
+
if (this.unavailable) {
|
|
182
|
+
throw new Error(`Owner questions are unavailable: ${this.unavailable}`);
|
|
183
|
+
}
|
|
184
|
+
const now = this.now();
|
|
185
|
+
this.enforceRateLimits(caller, now);
|
|
186
|
+
|
|
187
|
+
const nonce = b64url(randomBytes(16));
|
|
188
|
+
const expiresAtSec = Math.floor(now / 1000) + input.timeoutSeconds;
|
|
189
|
+
const payload: QuestionPayload = {
|
|
190
|
+
v: 1,
|
|
191
|
+
n: nonce,
|
|
192
|
+
s: caller,
|
|
193
|
+
t: input.target,
|
|
194
|
+
e: expiresAtSec,
|
|
195
|
+
b: input.buttons,
|
|
196
|
+
q: input.question,
|
|
197
|
+
ti: input.title,
|
|
198
|
+
};
|
|
199
|
+
const requestId = this.signRequest(payload);
|
|
200
|
+
|
|
201
|
+
const data: Record<string, unknown> = {
|
|
202
|
+
tag: this.tagFor(nonce),
|
|
203
|
+
actions: input.buttons.map((title, index) => ({
|
|
204
|
+
action: this.actionId(nonce, index, expiresAtSec, input.target),
|
|
205
|
+
title,
|
|
206
|
+
})),
|
|
207
|
+
// Stays until answered: not dismissed by tapping the body (sticky) or by
|
|
208
|
+
// swiping (persistent, needs the tag); the phone removes it at expiry.
|
|
209
|
+
sticky: true,
|
|
210
|
+
persistent: true,
|
|
211
|
+
priority: 'high',
|
|
212
|
+
ttl: 0,
|
|
213
|
+
timeout: input.timeoutSeconds,
|
|
214
|
+
};
|
|
215
|
+
if (input.channel) data.channel = input.channel;
|
|
216
|
+
if (input.importance) data.importance = input.importance;
|
|
217
|
+
|
|
218
|
+
// Reserve the slot before sending, so concurrent calls cannot all pass the limits.
|
|
219
|
+
this.reserve(caller, nonce, expiresAtSec * 1000, now);
|
|
220
|
+
try {
|
|
221
|
+
await this.deps.notify(input.target, { title: input.title, message: input.question, data });
|
|
222
|
+
} catch {
|
|
223
|
+
// The underlying error can carry request details; neither the caller
|
|
224
|
+
// nor this log gets its text.
|
|
225
|
+
this.release(caller, nonce, now);
|
|
226
|
+
logger.warn('Owner questions: sending the notification failed', { target: input.target });
|
|
227
|
+
throw new Error(`Could not send the notification through Home Assistant (is '${input.target}' a valid notify target?)`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
this.known.set(nonce, { target: input.target, title: input.title, buttons: input.buttons, expiresAt: expiresAtSec * 1000 });
|
|
231
|
+
// Count from now, after delivery: the signed expiry is what matters.
|
|
232
|
+
this.scheduleExpiry(nonce, Math.max(expiresAtSec * 1000 - this.now(), 0));
|
|
233
|
+
logger.info('Owner question sent', { caller, target: input.target, buttons: input.buttons.length, expiresAt: expiresAtSec });
|
|
234
|
+
|
|
235
|
+
return { requestId, expiresAt: new Date(expiresAtSec * 1000).toISOString() };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async getAnswer(requestId: string, caller: string, waitSeconds: number): Promise<OwnerAnswer> {
|
|
239
|
+
const payload = this.verifyRequest(requestId);
|
|
240
|
+
if (!payload) {
|
|
241
|
+
return { status: 'unknown', reason: 'Not a valid question id from this server (or the server secret changed)' };
|
|
242
|
+
}
|
|
243
|
+
this.assertOwner(payload, caller);
|
|
244
|
+
|
|
245
|
+
const settled = this.settledAnswer(payload);
|
|
246
|
+
if (settled || waitSeconds <= 0) {
|
|
247
|
+
return settled ?? this.pendingAnswer(payload);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const untilExpiry = payload.e * 1000 - this.now();
|
|
251
|
+
await this.waitForOutcome(payload.n, Math.min(waitSeconds * 1000, Math.max(untilExpiry, 0)));
|
|
252
|
+
return this.settledAnswer(payload) ?? this.pendingAnswer(payload);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async cancel(requestId: string, caller: string): Promise<OwnerAnswer> {
|
|
256
|
+
const payload = this.verifyRequest(requestId);
|
|
257
|
+
if (!payload) {
|
|
258
|
+
return { status: 'unknown', reason: 'Not a valid question id from this server (or the server secret changed)' };
|
|
259
|
+
}
|
|
260
|
+
this.assertOwner(payload, caller);
|
|
261
|
+
|
|
262
|
+
const settled = this.settledAnswer(payload);
|
|
263
|
+
if (settled) {
|
|
264
|
+
return settled;
|
|
265
|
+
}
|
|
266
|
+
this.settle(payload.n, { status: 'cancelled', cancelledAt: this.now() }, payload.e * 1000);
|
|
267
|
+
await this.replaceNotification(payload.n, payload.t, payload.ti, 'Cancelled - no answer needed');
|
|
268
|
+
return this.settledAnswer(payload)!;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Handle a `mobile_app_notification_action` event. Exposed for tests. */
|
|
272
|
+
handleActionEvent(event: ActionEvent): void {
|
|
273
|
+
const parsed = this.parseActionId(event.data.action);
|
|
274
|
+
if (!parsed) {
|
|
275
|
+
return; // not one of ours
|
|
276
|
+
}
|
|
277
|
+
if (event.origin !== 'REMOTE' || !event.context.user_id) {
|
|
278
|
+
logger.warn('Owner questions: ignored a tap not coming from a mobile app', { origin: event.origin });
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (this.deps.allowedUserIds?.length && !this.deps.allowedUserIds.includes(event.context.user_id)) {
|
|
282
|
+
logger.warn('Owner questions: ignored a tap from a Home Assistant user that may not answer');
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const { nonce, index, expiresAtSec, target } = parsed;
|
|
286
|
+
const known = this.known.get(nonce);
|
|
287
|
+
if (this.now() >= expiresAtSec * 1000) {
|
|
288
|
+
logger.info('Owner questions: ignored a tap after expiry');
|
|
289
|
+
void this.replaceNotification(nonce, target, known?.title ?? 'Question', 'Expired - the answer was not recorded');
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (this.outcomes.has(nonce)) {
|
|
293
|
+
return; // first tap wins
|
|
294
|
+
}
|
|
295
|
+
this.settle(nonce, { status: 'answered', index, answeredAt: this.now(), answeredBy: event.context.user_id }, expiresAtSec * 1000);
|
|
296
|
+
logger.info('Owner question answered', { index });
|
|
297
|
+
const label = known?.buttons[index];
|
|
298
|
+
void this.replaceNotification(nonce, target, known?.title ?? 'Question', label ? `Answered: ${label}` : 'Answer recorded');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ---- internals -------------------------------------------------------
|
|
302
|
+
|
|
303
|
+
private signRequest(payload: QuestionPayload): string {
|
|
304
|
+
const body = `${REQUEST_PREFIX}.${b64url(Buffer.from(JSON.stringify(payload), 'utf8'))}`;
|
|
305
|
+
return `${body}.${b64url(this.hmac(`request|${body}`))}`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private verifyRequest(requestId: string): QuestionPayload | null {
|
|
309
|
+
const parts = typeof requestId === 'string' ? requestId.split('.') : [];
|
|
310
|
+
if (parts.length !== 3 || parts[0] !== REQUEST_PREFIX) {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
const body = `${parts[0]}.${parts[1]}`;
|
|
314
|
+
if (!this.safeEqual(parts[2], b64url(this.hmac(`request|${body}`)))) {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as QuestionPayload;
|
|
319
|
+
return payload.v === 1 ? payload : null;
|
|
320
|
+
} catch {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
private actionId(nonce: string, index: number, expiresAtSec: number, target: string): string {
|
|
326
|
+
const sig = b64url(this.hmac(`action|${nonce}|${index}|${expiresAtSec}|${target}`)).slice(0, 22);
|
|
327
|
+
return `${ACTION_PREFIX}.${nonce}.${index}.${expiresAtSec}.${target}.${sig}`;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private parseActionId(action: unknown): { nonce: string; index: number; expiresAtSec: number; target: string } | null {
|
|
331
|
+
if (typeof action !== 'string' || !action.startsWith(`${ACTION_PREFIX}.`)) {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
const match = /^MCPASK\.([A-Za-z0-9_-]{22})\.([0-2])\.(\d{1,12})\.(mobile_app_[a-z0-9_]{1,64})\.([A-Za-z0-9_-]{22})$/.exec(action);
|
|
335
|
+
if (!match) {
|
|
336
|
+
logger.warn('Owner questions: ignored a malformed action id');
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const [, nonce, index, expires, target, sig] = match;
|
|
340
|
+
const expected = b64url(this.hmac(`action|${nonce}|${index}|${expires}|${target}`)).slice(0, 22);
|
|
341
|
+
if (!this.safeEqual(sig, expected)) {
|
|
342
|
+
logger.warn('Owner questions: ignored a tap with an invalid signature');
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
return { nonce, index: Number(index), expiresAtSec: Number(expires), target };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private hmac(message: string): Buffer {
|
|
349
|
+
return createHmac('sha256', this.key).update(message).digest();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
private safeEqual(a: string, b: string): boolean {
|
|
353
|
+
const left = Buffer.from(a);
|
|
354
|
+
const right = Buffer.from(b);
|
|
355
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private tagFor(nonce: string): string {
|
|
359
|
+
return `mcpask-${nonce}`;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private assertOwner(payload: QuestionPayload, caller: string): void {
|
|
363
|
+
if (payload.s !== caller) {
|
|
364
|
+
throw new Error('This question was asked by a different client');
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private settledAnswer(payload: QuestionPayload): OwnerAnswer | null {
|
|
369
|
+
const base = { question: payload.q, buttons: payload.b };
|
|
370
|
+
const outcome = this.outcomes.get(payload.n);
|
|
371
|
+
if (outcome?.status === 'answered') {
|
|
372
|
+
return {
|
|
373
|
+
status: 'answered',
|
|
374
|
+
index: outcome.index,
|
|
375
|
+
button: payload.b[outcome.index] ?? `#${outcome.index}`,
|
|
376
|
+
answeredAt: new Date(outcome.answeredAt).toISOString(),
|
|
377
|
+
answeredBy: outcome.answeredBy,
|
|
378
|
+
...base,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
if (outcome?.status === 'cancelled') {
|
|
382
|
+
return { status: 'cancelled', cancelledAt: new Date(outcome.cancelledAt).toISOString(), ...base };
|
|
383
|
+
}
|
|
384
|
+
if (this.now() >= payload.e * 1000) {
|
|
385
|
+
return { status: 'timeout', expiredAt: new Date(payload.e * 1000).toISOString(), ...base };
|
|
386
|
+
}
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private pendingAnswer(payload: QuestionPayload): OwnerAnswer {
|
|
391
|
+
return { status: 'pending', expiresAt: new Date(payload.e * 1000).toISOString(), question: payload.q, buttons: payload.b };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private settle(nonce: string, outcome: Outcome, expiresAtMs: number): void {
|
|
395
|
+
this.outcomes.set(nonce, { ...outcome, expiresAt: expiresAtMs });
|
|
396
|
+
this.known.delete(nonce);
|
|
397
|
+
for (const questions of this.open.values()) {
|
|
398
|
+
questions.delete(nonce);
|
|
399
|
+
}
|
|
400
|
+
const timer = this.expiryTimers.get(nonce);
|
|
401
|
+
if (timer) {
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
this.expiryTimers.delete(nonce);
|
|
404
|
+
}
|
|
405
|
+
this.wake(nonce);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private wake(nonce: string): void {
|
|
409
|
+
for (const resolve of this.waiters.get(nonce) ?? []) {
|
|
410
|
+
resolve();
|
|
411
|
+
}
|
|
412
|
+
this.waiters.delete(nonce);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private waitForOutcome(nonce: string, ms: number): Promise<void> {
|
|
416
|
+
return new Promise((resolve) => {
|
|
417
|
+
const waiters = this.waiters.get(nonce) ?? new Set<() => void>();
|
|
418
|
+
this.waiters.set(nonce, waiters);
|
|
419
|
+
const done = () => {
|
|
420
|
+
clearTimeout(timer);
|
|
421
|
+
waiters.delete(done);
|
|
422
|
+
if (waiters.size === 0 && this.waiters.get(nonce) === waiters) {
|
|
423
|
+
this.waiters.delete(nonce);
|
|
424
|
+
}
|
|
425
|
+
resolve();
|
|
426
|
+
};
|
|
427
|
+
const timer = setTimeout(done, ms);
|
|
428
|
+
waiters.add(done);
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private scheduleExpiry(nonce: string, ms: number): void {
|
|
433
|
+
// Node timers overflow above ~24.8 days; questions last at most 7 days.
|
|
434
|
+
const timer = setTimeout(() => {
|
|
435
|
+
this.expiryTimers.delete(nonce);
|
|
436
|
+
if (this.outcomes.has(nonce)) {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
for (const questions of this.open.values()) {
|
|
440
|
+
questions.delete(nonce);
|
|
441
|
+
}
|
|
442
|
+
this.wake(nonce);
|
|
443
|
+
const known = this.known.get(nonce);
|
|
444
|
+
this.known.delete(nonce);
|
|
445
|
+
if (known) {
|
|
446
|
+
void this.replaceNotification(nonce, known.target, known.title, 'Expired - treated as no');
|
|
447
|
+
}
|
|
448
|
+
}, ms);
|
|
449
|
+
timer.unref?.();
|
|
450
|
+
this.expiryTimers.set(nonce, timer);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private async replaceNotification(nonce: string, target: string, title: string, message: string): Promise<void> {
|
|
454
|
+
try {
|
|
455
|
+
// Same tag replaces the question; no actions, dismissible, gone after a while.
|
|
456
|
+
await this.deps.notify(target, {
|
|
457
|
+
title,
|
|
458
|
+
message,
|
|
459
|
+
data: { tag: this.tagFor(nonce), sticky: false, persistent: false, timeout: CONFIRMATION_SECONDS },
|
|
460
|
+
});
|
|
461
|
+
} catch {
|
|
462
|
+
logger.warn('Owner questions: could not update the notification', { target });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private enforceRateLimits(caller: string, now: number): void {
|
|
467
|
+
const open = this.open.get(caller);
|
|
468
|
+
if (open) {
|
|
469
|
+
for (const [nonce, expiresAt] of open) {
|
|
470
|
+
if (expiresAt <= now) open.delete(nonce);
|
|
471
|
+
}
|
|
472
|
+
if (open.size >= LIMITS.maxOpenPerCaller) {
|
|
473
|
+
throw new Error(`Too many open questions (${open.size}); answer, cancel or wait for one to expire first`);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const recent = (this.asked.get(caller) ?? []).filter((t) => t > now - 60 * 60 * 1000);
|
|
477
|
+
if (recent.length >= LIMITS.maxPerCallerPerHour) {
|
|
478
|
+
throw new Error(`Too many questions in the last hour (limit ${LIMITS.maxPerCallerPerHour})`);
|
|
479
|
+
}
|
|
480
|
+
this.asked.set(caller, recent);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private reserve(caller: string, nonce: string, expiresAtMs: number, now: number): void {
|
|
484
|
+
const open = this.open.get(caller) ?? new Map<string, number>();
|
|
485
|
+
open.set(nonce, expiresAtMs);
|
|
486
|
+
this.open.set(caller, open);
|
|
487
|
+
const asked = this.asked.get(caller) ?? [];
|
|
488
|
+
asked.push(now);
|
|
489
|
+
this.asked.set(caller, asked);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
private release(caller: string, nonce: string, now: number): void {
|
|
493
|
+
this.open.get(caller)?.delete(nonce);
|
|
494
|
+
const asked = this.asked.get(caller);
|
|
495
|
+
const index = asked?.lastIndexOf(now) ?? -1;
|
|
496
|
+
if (asked && index >= 0) asked.splice(index, 1);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Periodic cleanup, independent of new activity: outcomes a day after their
|
|
501
|
+
* question expired (a caller polling that late sees "timeout"), labels of
|
|
502
|
+
* expired questions, and rate-limit entries that no longer count.
|
|
503
|
+
* Exposed for tests.
|
|
504
|
+
*/
|
|
505
|
+
sweep(): void {
|
|
506
|
+
const now = this.now();
|
|
507
|
+
for (const [nonce, outcome] of this.outcomes) {
|
|
508
|
+
if (outcome.expiresAt + OUTCOME_RETENTION_MS < now) this.outcomes.delete(nonce);
|
|
509
|
+
}
|
|
510
|
+
for (const [nonce, known] of this.known) {
|
|
511
|
+
if (known.expiresAt < now) this.known.delete(nonce);
|
|
512
|
+
}
|
|
513
|
+
for (const [caller, open] of this.open) {
|
|
514
|
+
for (const [nonce, expiresAt] of open) {
|
|
515
|
+
if (expiresAt <= now) open.delete(nonce);
|
|
516
|
+
}
|
|
517
|
+
if (open.size === 0) this.open.delete(caller);
|
|
518
|
+
}
|
|
519
|
+
for (const [caller, asked] of this.asked) {
|
|
520
|
+
const recent = asked.filter((t) => t > now - 60 * 60 * 1000);
|
|
521
|
+
if (recent.length === 0) this.asked.delete(caller);
|
|
522
|
+
else this.asked.set(caller, recent);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Sizes of the in-memory state, for tests and diagnostics. */
|
|
527
|
+
stateSize(): { outcomes: number; known: number; open: number; asked: number; waiters: number } {
|
|
528
|
+
return {
|
|
529
|
+
outcomes: this.outcomes.size,
|
|
530
|
+
known: this.known.size,
|
|
531
|
+
open: this.open.size,
|
|
532
|
+
asked: this.asked.size,
|
|
533
|
+
waiters: this.waiters.size,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
}
|
package/src/server/common.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { RestAction } from '../tools/infra/index.js';
|
|
|
15
15
|
import { registerAllResources } from '../resources/index.js';
|
|
16
16
|
import { generateInstructions } from './instructions.js';
|
|
17
17
|
import { logger } from '../utils/logger.js';
|
|
18
|
+
import type { OwnerQuestionService } from '../ownerQuestions/service.js';
|
|
18
19
|
import { VERSION } from '../version.js';
|
|
19
20
|
|
|
20
21
|
export interface CreateServerOptions {
|
|
@@ -32,10 +33,12 @@ export interface CreateServerOptions {
|
|
|
32
33
|
* Execution-time RBAC in wrapToolHandler still applies either way.
|
|
33
34
|
*/
|
|
34
35
|
callerPermissions?: number;
|
|
36
|
+
/** Owner questions service (askOwner & co.), when running. */
|
|
37
|
+
ownerQuestions?: OwnerQuestionService;
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
export function createServer(options: CreateServerOptions): McpServer {
|
|
38
|
-
const { haClient, omadaClient, aiClient, restActions, toolRegistrationMode, callerPermissions } = options;
|
|
41
|
+
const { haClient, omadaClient, aiClient, restActions, toolRegistrationMode, callerPermissions, ownerQuestions } = options;
|
|
39
42
|
logger.debug('Creating MCP server instance');
|
|
40
43
|
|
|
41
44
|
// Generate instructions based on enabled plugins
|
|
@@ -77,6 +80,7 @@ export function createServer(options: CreateServerOptions): McpServer {
|
|
|
77
80
|
aiClient,
|
|
78
81
|
restActions,
|
|
79
82
|
toolRegistrationMode,
|
|
83
|
+
ownerQuestions,
|
|
80
84
|
});
|
|
81
85
|
} finally {
|
|
82
86
|
server.registerTool = originalRegisterTool;
|
package/src/server/http.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { handleEventSubscription } from './eventSubscription.js';
|
|
|
15
15
|
import { RateLimiter } from './rateLimiter.js';
|
|
16
16
|
import { createAuthMiddleware } from './auth.js';
|
|
17
17
|
import { sanitizeError } from '../utils/sanitizeError.js';
|
|
18
|
+
import { OwnerQuestionService } from '../ownerQuestions/service.js';
|
|
18
19
|
import {
|
|
19
20
|
LEGACY_BINDINGS,
|
|
20
21
|
resolveChatBindings,
|
|
@@ -343,23 +344,45 @@ export async function startHttpServer(options: HttpServerOptions): Promise<void>
|
|
|
343
344
|
audience: config.authAudience,
|
|
344
345
|
});
|
|
345
346
|
|
|
346
|
-
// Initialize event subscriber
|
|
347
|
+
// Initialize the HA event subscriber when SSE events or owner questions need it
|
|
347
348
|
let eventSubscriber: EventSubscriber | null = null;
|
|
348
|
-
if (config.sseEventsEnabled && config.baseUrl && config.token) {
|
|
349
|
+
if ((config.sseEventsEnabled || config.ownerQuestionsEnabled) && config.baseUrl && config.token) {
|
|
349
350
|
eventSubscriber = new EventSubscriber({
|
|
350
351
|
baseUrl: config.baseUrl,
|
|
351
352
|
token: config.token,
|
|
353
|
+
strictSsl: config.strictSsl,
|
|
352
354
|
});
|
|
353
355
|
|
|
354
|
-
// Connect to Home Assistant WebSocket
|
|
356
|
+
// Connect to Home Assistant WebSocket. On failure the subscriber keeps
|
|
357
|
+
// retrying in the background; it is kept (not dropped) so events and owner
|
|
358
|
+
// questions start working as soon as Home Assistant is reachable.
|
|
355
359
|
try {
|
|
356
360
|
await eventSubscriber.connect();
|
|
357
361
|
logger.info('Event subscriber connected to Home Assistant');
|
|
358
362
|
} catch (error) {
|
|
359
|
-
logger.warn('
|
|
363
|
+
logger.warn('Home Assistant WebSocket not reachable yet; retrying in the background', {
|
|
364
|
+
error: error instanceof Error ? error.message : String(error),
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Owner questions (askOwner & co.) listen for notification taps on the subscriber.
|
|
370
|
+
let ownerQuestions: OwnerQuestionService | undefined;
|
|
371
|
+
if (config.ownerQuestionsEnabled && eventSubscriber && client) {
|
|
372
|
+
const subscriber = eventSubscriber;
|
|
373
|
+
const service = new OwnerQuestionService({
|
|
374
|
+
notify: (target, serviceData) => client.callService({ domain: 'notify', service: target, service_data: serviceData }),
|
|
375
|
+
subscribe: (eventType, callback, onRejected) => subscriber.subscribeEventType(eventType, callback, onRejected),
|
|
376
|
+
secret: config.authSecret,
|
|
377
|
+
allowedUserIds: config.ownerQuestionsHaUsers,
|
|
378
|
+
});
|
|
379
|
+
try {
|
|
380
|
+
await service.start();
|
|
381
|
+
ownerQuestions = service;
|
|
382
|
+
} catch (error) {
|
|
383
|
+
logger.warn('Owner questions unavailable: could not subscribe to notification taps', {
|
|
360
384
|
error: error instanceof Error ? error.message : String(error),
|
|
361
385
|
});
|
|
362
|
-
eventSubscriber = null;
|
|
363
386
|
}
|
|
364
387
|
}
|
|
365
388
|
|
|
@@ -482,7 +505,7 @@ export async function startHttpServer(options: HttpServerOptions): Promise<void>
|
|
|
482
505
|
const existingState = sessionId ? sessions.get(sessionId) : undefined;
|
|
483
506
|
|
|
484
507
|
const body = req.method !== 'GET' ? await parseBody(req) : undefined;
|
|
485
|
-
const streamOptions: StreamTransportOptions = { haClient: client, omadaClient, aiClient, config };
|
|
508
|
+
const streamOptions: StreamTransportOptions = { haClient: client, omadaClient, aiClient, config, ownerQuestions };
|
|
486
509
|
const state = await handleStreamRequest(streamOptions, req, res, body, existingState);
|
|
487
510
|
|
|
488
511
|
if (state && config.stateful && sessionId) {
|
|
@@ -562,6 +585,7 @@ export async function startHttpServer(options: HttpServerOptions): Promise<void>
|
|
|
562
585
|
sessions.clear();
|
|
563
586
|
|
|
564
587
|
// Close event subscriber
|
|
588
|
+
ownerQuestions?.stop();
|
|
565
589
|
if (eventSubscriber) {
|
|
566
590
|
eventSubscriber.disconnect();
|
|
567
591
|
}
|
package/src/server/stream.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { LocalAIClient } from '../localAI/index.js';
|
|
|
12
12
|
import type { OmadaClient } from '../omadaClient/index.js';
|
|
13
13
|
import { logger } from '../utils/logger.js';
|
|
14
14
|
import { createServer } from './common.js';
|
|
15
|
+
import type { OwnerQuestionService } from '../ownerQuestions/service.js';
|
|
15
16
|
import type { AuthenticatedRequest } from './auth.js';
|
|
16
17
|
|
|
17
18
|
interface StreamTransportState {
|
|
@@ -27,6 +28,7 @@ export interface StreamTransportOptions {
|
|
|
27
28
|
omadaClient?: OmadaClient;
|
|
28
29
|
aiClient?: LocalAIClient;
|
|
29
30
|
config: EnvironmentConfig;
|
|
31
|
+
ownerQuestions?: OwnerQuestionService;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export interface TransportSecurityOptions {
|
|
@@ -94,11 +96,12 @@ export function buildTransportSecurityOptions(config: EnvironmentConfig): Transp
|
|
|
94
96
|
* This implements the MCP protocol version 2025-03-26
|
|
95
97
|
*/
|
|
96
98
|
export function createStreamTransport(options: StreamTransportOptions, callerPermissions?: number): StreamTransportState {
|
|
97
|
-
const { haClient, omadaClient, aiClient, config } = options;
|
|
99
|
+
const { haClient, omadaClient, aiClient, config, ownerQuestions } = options;
|
|
98
100
|
const mcpServer = createServer({
|
|
99
101
|
haClient,
|
|
100
102
|
omadaClient,
|
|
101
103
|
aiClient,
|
|
104
|
+
ownerQuestions,
|
|
102
105
|
restActions: config.restActions,
|
|
103
106
|
toolRegistrationMode: config.toolRegistrationMode,
|
|
104
107
|
// Hide tools this caller can never use from tools/list (RBAC still enforced per call).
|
package/src/tools/common.ts
CHANGED
|
@@ -147,7 +147,10 @@ export function wrapToolHandler<T>(
|
|
|
147
147
|
}, true);
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
|
|
150
|
+
// Arguments can carry message text, entity names or MAC addresses: they are
|
|
151
|
+
// logged at debug level only, never in normal (info) operation.
|
|
152
|
+
logger.info('Tool invoked', { tool: name, sessionId });
|
|
153
|
+
logger.debug('Tool arguments', { tool: name, sessionId, args: safeSerialize(args) });
|
|
151
154
|
|
|
152
155
|
try {
|
|
153
156
|
const result = await handler(args, extra);
|