@coffeerunhobby/mcp-ha-connect 2.1.1 → 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.
Files changed (70) hide show
  1. package/README.md +19 -3
  2. package/dist/config.d.ts +4 -0
  3. package/dist/config.js +6 -0
  4. package/dist/config.js.map +1 -1
  5. package/dist/haClient/automations.d.ts +18 -2
  6. package/dist/haClient/automations.js +25 -7
  7. package/dist/haClient/automations.js.map +1 -1
  8. package/dist/haClient/events.d.ts +60 -7
  9. package/dist/haClient/events.js +252 -47
  10. package/dist/haClient/events.js.map +1 -1
  11. package/dist/haClient/index.d.ts +2 -1
  12. package/dist/haClient/index.js +4 -3
  13. package/dist/haClient/index.js.map +1 -1
  14. package/dist/haClient/wsCommand.d.ts +16 -0
  15. package/dist/haClient/wsCommand.js +36 -0
  16. package/dist/haClient/wsCommand.js.map +1 -0
  17. package/dist/ownerQuestions/service.d.ts +167 -0
  18. package/dist/ownerQuestions/service.js +439 -0
  19. package/dist/ownerQuestions/service.js.map +1 -0
  20. package/dist/server/common.d.ts +3 -0
  21. package/dist/server/common.js +2 -1
  22. package/dist/server/common.js.map +1 -1
  23. package/dist/server/http.js +30 -6
  24. package/dist/server/http.js.map +1 -1
  25. package/dist/server/stream.d.ts +2 -0
  26. package/dist/server/stream.js +2 -1
  27. package/dist/server/stream.js.map +1 -1
  28. package/dist/tools/common.d.ts +1 -1
  29. package/dist/tools/common.js +4 -1
  30. package/dist/tools/common.js.map +1 -1
  31. package/dist/tools/homeassistant/askOwner.d.ts +29 -0
  32. package/dist/tools/homeassistant/askOwner.js +85 -0
  33. package/dist/tools/homeassistant/askOwner.js.map +1 -0
  34. package/dist/tools/homeassistant/getAutomationTrace.d.ts +5 -0
  35. package/dist/tools/homeassistant/getAutomationTrace.js +10 -5
  36. package/dist/tools/homeassistant/getAutomationTrace.js.map +1 -1
  37. package/dist/tools/index.d.ts +3 -0
  38. package/dist/tools/index.js +5 -1
  39. package/dist/tools/index.js.map +1 -1
  40. package/dist/utils/plainText.d.ts +22 -0
  41. package/dist/utils/plainText.js +39 -0
  42. package/dist/utils/plainText.js.map +1 -0
  43. package/dist/version.d.ts +1 -1
  44. package/dist/version.js +1 -1
  45. package/docs/CHANGELOG.md +15 -0
  46. package/openapi.json +1 -1
  47. package/package.json +1 -1
  48. package/src/config.ts +10 -0
  49. package/src/haClient/automations.ts +39 -7
  50. package/src/haClient/events.ts +289 -56
  51. package/src/haClient/index.ts +10 -4
  52. package/src/haClient/wsCommand.ts +44 -0
  53. package/src/ownerQuestions/service.ts +536 -0
  54. package/src/server/common.ts +5 -1
  55. package/src/server/http.ts +30 -6
  56. package/src/server/stream.ts +4 -1
  57. package/src/tools/common.ts +4 -1
  58. package/src/tools/homeassistant/askOwner.ts +133 -0
  59. package/src/tools/homeassistant/getAutomationTrace.ts +13 -7
  60. package/src/tools/index.ts +8 -1
  61. package/src/utils/plainText.ts +48 -0
  62. package/src/version.ts +1 -1
  63. package/tests/config.test.ts +12 -0
  64. package/tests/haClient/automationTrace.test.ts +59 -0
  65. package/tests/haClient/automations.test.ts +16 -0
  66. package/tests/haClient/events.test.ts +455 -0
  67. package/tests/haClient/eventsTls.test.ts +52 -0
  68. package/tests/ownerQuestions/service.test.ts +499 -0
  69. package/tests/ownerQuestions/tools.test.ts +186 -0
  70. package/tests/tools/homeassistant/handlers.test.ts +10 -1
@@ -18,7 +18,8 @@ import type {
18
18
  } from '../types/index.js';
19
19
  import { logger } from '../utils/logger.js';
20
20
 
21
- import { AutomationOperations } from './automations.js';
21
+ import { AutomationOperations, type AutomationTraceSummary } from './automations.js';
22
+ import { createHaWebSocketCommand } from './wsCommand.js';
22
23
  import { ConfigOperations } from './config.js';
23
24
  import { DeviceOperations } from './devices.js';
24
25
  import { EntityOperations } from './entities.js';
@@ -67,7 +68,12 @@ export class HaClient {
67
68
  this.stateOps = new StateOperations(this.request);
68
69
  this.serviceOps = new ServiceOperations(this.request);
69
70
  this.entityOps = new EntityOperations(this.stateOps);
70
- this.automationOps = new AutomationOperations(this.stateOps, this.serviceOps, this.request);
71
+ this.automationOps = new AutomationOperations(
72
+ this.stateOps,
73
+ this.serviceOps,
74
+ this.request,
75
+ createHaWebSocketCommand({ baseUrl: config.baseUrl, token: config.token, strictSsl: config.strictSsl })
76
+ );
71
77
  this.historyOps = new HistoryOperations(this.request);
72
78
  this.updateOps = new UpdateOperations(this.entityOps);
73
79
  this.configOps = new ConfigOperations(this.request);
@@ -226,8 +232,8 @@ export class HaClient {
226
232
  /**
227
233
  * Get automation execution trace
228
234
  */
229
- async getAutomationTrace(entityId: string): Promise<unknown[]> {
230
- return this.automationOps.getAutomationTrace(entityId);
235
+ async getAutomationTrace(entityId: string, limit?: number): Promise<AutomationTraceSummary[]> {
236
+ return this.automationOps.getAutomationTrace(entityId, limit);
231
237
  }
232
238
 
233
239
  // ===== History Operations =====
@@ -0,0 +1,44 @@
1
+ /**
2
+ * One-shot Home Assistant WebSocket command: connect, authenticate, send one
3
+ * command, return its result, disconnect. For the few HA APIs that exist only
4
+ * over WebSocket (e.g. automation traces), usable in every transport mode.
5
+ */
6
+
7
+ import { EventSubscriber } from './events.js';
8
+
9
+ export type HaWebSocketCommand = <T = unknown>(command: { type: string; [key: string]: unknown }) => Promise<T>;
10
+
11
+ export function createHaWebSocketCommand(config: {
12
+ baseUrl: string;
13
+ token: string;
14
+ strictSsl?: boolean;
15
+ /** One deadline for connecting, authenticating and the command (ms). Default 30 s. */
16
+ timeoutMs?: number;
17
+ }): HaWebSocketCommand {
18
+ const timeoutMs = config.timeoutMs ?? 30000;
19
+ return async <T>(command: { type: string; [key: string]: unknown }): Promise<T> => {
20
+ const connection = new EventSubscriber({
21
+ baseUrl: config.baseUrl,
22
+ token: config.token,
23
+ strictSsl: config.strictSsl,
24
+ maxReconnectAttempts: 0,
25
+ connectTimeout: timeoutMs,
26
+ });
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ const deadline = new Promise<never>((_, reject) => {
29
+ timer = setTimeout(() => reject(new Error(`Home Assistant command '${command.type}' timed out`)), timeoutMs);
30
+ });
31
+ const work = (async () => {
32
+ await connection.connect();
33
+ return await connection.sendCommand<T>(command, timeoutMs);
34
+ })();
35
+ // If the deadline wins, the abandoned attempt still settles later: observe it.
36
+ work.catch(() => undefined);
37
+ try {
38
+ return await Promise.race([work, deadline]);
39
+ } finally {
40
+ clearTimeout(timer);
41
+ connection.disconnect();
42
+ }
43
+ };
44
+ }
@@ -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
+ }
@@ -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;