@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.
Files changed (74) 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/omadaClient/site.js +15 -2
  18. package/dist/omadaClient/site.js.map +1 -1
  19. package/dist/ownerQuestions/service.d.ts +167 -0
  20. package/dist/ownerQuestions/service.js +439 -0
  21. package/dist/ownerQuestions/service.js.map +1 -0
  22. package/dist/server/common.d.ts +3 -0
  23. package/dist/server/common.js +2 -1
  24. package/dist/server/common.js.map +1 -1
  25. package/dist/server/http.js +30 -6
  26. package/dist/server/http.js.map +1 -1
  27. package/dist/server/stream.d.ts +2 -0
  28. package/dist/server/stream.js +2 -1
  29. package/dist/server/stream.js.map +1 -1
  30. package/dist/tools/common.d.ts +1 -1
  31. package/dist/tools/common.js +4 -1
  32. package/dist/tools/common.js.map +1 -1
  33. package/dist/tools/homeassistant/askOwner.d.ts +29 -0
  34. package/dist/tools/homeassistant/askOwner.js +85 -0
  35. package/dist/tools/homeassistant/askOwner.js.map +1 -0
  36. package/dist/tools/homeassistant/getAutomationTrace.d.ts +5 -0
  37. package/dist/tools/homeassistant/getAutomationTrace.js +10 -5
  38. package/dist/tools/homeassistant/getAutomationTrace.js.map +1 -1
  39. package/dist/tools/index.d.ts +3 -0
  40. package/dist/tools/index.js +5 -1
  41. package/dist/tools/index.js.map +1 -1
  42. package/dist/utils/plainText.d.ts +22 -0
  43. package/dist/utils/plainText.js +39 -0
  44. package/dist/utils/plainText.js.map +1 -0
  45. package/dist/version.d.ts +1 -1
  46. package/dist/version.js +1 -1
  47. package/docs/CHANGELOG.md +19 -0
  48. package/openapi.json +1 -1
  49. package/package.json +1 -1
  50. package/src/config.ts +10 -0
  51. package/src/haClient/automations.ts +39 -7
  52. package/src/haClient/events.ts +289 -56
  53. package/src/haClient/index.ts +10 -4
  54. package/src/haClient/wsCommand.ts +44 -0
  55. package/src/omadaClient/site.ts +17 -2
  56. package/src/ownerQuestions/service.ts +536 -0
  57. package/src/server/common.ts +5 -1
  58. package/src/server/http.ts +30 -6
  59. package/src/server/stream.ts +4 -1
  60. package/src/tools/common.ts +4 -1
  61. package/src/tools/homeassistant/askOwner.ts +133 -0
  62. package/src/tools/homeassistant/getAutomationTrace.ts +13 -7
  63. package/src/tools/index.ts +8 -1
  64. package/src/utils/plainText.ts +48 -0
  65. package/src/version.ts +1 -1
  66. package/tests/config.test.ts +12 -0
  67. package/tests/haClient/automationTrace.test.ts +59 -0
  68. package/tests/haClient/automations.test.ts +16 -0
  69. package/tests/haClient/events.test.ts +455 -0
  70. package/tests/haClient/eventsTls.test.ts +52 -0
  71. package/tests/omadaClient/ntp.test.ts +15 -0
  72. package/tests/ownerQuestions/service.test.ts +499 -0
  73. package/tests/ownerQuestions/tools.test.ts +186 -0
  74. package/tests/tools/homeassistant/handlers.test.ts +10 -1
@@ -69,16 +69,29 @@ export function buildSiteUpdateBody(site, ntpServers, ntpEnable) {
69
69
  dst.enable = enable;
70
70
  if (mode !== undefined)
71
71
  dst.mode = mode;
72
- if (start !== undefined)
72
+ // With DST off the controller returns start/end as `{}` but rejects them on
73
+ // write ("should not be null"), so only complete points are sent back.
74
+ if (isCompleteDstTime(start))
73
75
  dst.start = start;
74
- if (end !== undefined)
76
+ if (isCompleteDstTime(end))
75
77
  dst.end = end;
76
78
  if (offset !== undefined)
77
79
  dst.offset = offset;
80
+ if (enable === true && (dst.start === undefined || dst.end === undefined)) {
81
+ throw new Error('Site has daylight saving enabled but an incomplete start/end; refusing to write');
82
+ }
78
83
  body.dst = dst;
79
84
  }
80
85
  return body;
81
86
  }
87
+ const DST_TIME_FIELDS = ['month', 'serial', 'day', 'hour', 'minute'];
88
+ function isCompleteDstTime(value) {
89
+ if (typeof value !== 'object' || value === null) {
90
+ return false;
91
+ }
92
+ const point = value;
93
+ return DST_TIME_FIELDS.every((field) => typeof point[field] === 'number');
94
+ }
82
95
  /**
83
96
  * Validate a configured default site (`OMADA_SITE_ID`) against the controller's
84
97
  * live site list.
@@ -1 +1 @@
1
- {"version":3,"file":"site.js","sourceRoot":"","sources":["../../src/omadaClient/site.ts"],"names":[],"mappings":"AAIA,wDAAwD;AACxD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,+EAA+E,CAAC;AAE5G,MAAM,SAAS,GAAG,WAAW,CAAC;AAE9B;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,OAAe;IAC3C,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,IAAI,OAAO,2EAA2E,CAAC;IAClG,CAAC;IACD,IAAI,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC1B,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,UAAU,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AC,IAAI;YACnB,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,IAAI,EAAE,EAAE;YACxE,KAAK,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE;YAClD,OAAO,EAAE,mBAAmB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC;SACvD,CAAC;IACN,CAAC;CACJ"}
@@ -0,0 +1,167 @@
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
+ export declare const ACTION_EVENT = "mobile_app_notification_action";
30
+ export declare const LIMITS: {
31
+ readonly questionChars: 256;
32
+ readonly titleChars: 60;
33
+ readonly buttonChars: 20;
34
+ readonly maxButtons: 3;
35
+ readonly minTimeoutSeconds: 60;
36
+ readonly maxTimeoutSeconds: number;
37
+ readonly defaultTimeoutSeconds: 600;
38
+ readonly maxWaitSeconds: 50;
39
+ readonly maxOpenPerCaller: 3;
40
+ readonly maxPerCallerPerHour: 30;
41
+ };
42
+ export interface AskOwnerInput {
43
+ question: string;
44
+ title: string;
45
+ buttons: string[];
46
+ target: string;
47
+ timeoutSeconds: number;
48
+ channel?: string;
49
+ importance?: 'high' | 'default' | 'low' | 'min';
50
+ }
51
+ export type OwnerAnswer = {
52
+ status: 'answered';
53
+ index: number;
54
+ button: string;
55
+ answeredAt: string;
56
+ answeredBy: string;
57
+ question: string;
58
+ buttons: string[];
59
+ } | {
60
+ status: 'pending';
61
+ expiresAt: string;
62
+ question: string;
63
+ buttons: string[];
64
+ } | {
65
+ status: 'timeout';
66
+ expiredAt: string;
67
+ question: string;
68
+ buttons: string[];
69
+ } | {
70
+ status: 'cancelled';
71
+ cancelledAt: string;
72
+ question: string;
73
+ buttons: string[];
74
+ } | {
75
+ status: 'unknown';
76
+ reason: string;
77
+ };
78
+ export interface OwnerQuestionDeps {
79
+ /** Calls `notify.<target>`. */
80
+ notify: (target: string, serviceData: Record<string, unknown>) => Promise<unknown>;
81
+ /**
82
+ * Subscribes to a Home Assistant event type. Rejects if Home Assistant refuses
83
+ * it now; `onRejected` reports a refusal seen later (e.g. after a reconnect).
84
+ */
85
+ subscribe: (eventType: string, callback: (event: ActionEvent) => void, onRejected: (error: Error) => void) => Promise<unknown>;
86
+ /** Key material for signing (the server's auth secret); a random key is used when absent. */
87
+ secret?: string;
88
+ /** HA user ids allowed to answer; empty or absent = any HA user. */
89
+ allowedUserIds?: string[];
90
+ now?: () => number;
91
+ }
92
+ export interface ActionEvent {
93
+ event_type: string;
94
+ data: {
95
+ action?: unknown;
96
+ [key: string]: unknown;
97
+ };
98
+ origin: string;
99
+ time_fired?: string;
100
+ context: {
101
+ user_id: string | null;
102
+ };
103
+ }
104
+ export declare class OwnerQuestionService {
105
+ private readonly deps;
106
+ private readonly key;
107
+ private readonly now;
108
+ /** Final outcomes by nonce, until the question's expiry passes. */
109
+ private readonly outcomes;
110
+ /** Open questions per caller sub: nonce -> expiry (ms). */
111
+ private readonly open;
112
+ /** Ask timestamps per caller sub, for the hourly cap. */
113
+ private readonly asked;
114
+ /** Pollers waiting for an outcome, by nonce. */
115
+ private readonly waiters;
116
+ /** Expiry timers by nonce (best effort: lost on restart; the phone also times out on its own). */
117
+ private readonly expiryTimers;
118
+ /** Labels and target of open questions, for nicer confirmations while the server stays up. */
119
+ private readonly known;
120
+ private sweepTimer;
121
+ /** Why questions cannot be answered right now (Home Assistant refused the tap subscription). */
122
+ private unavailable;
123
+ constructor(deps: OwnerQuestionDeps);
124
+ start(): Promise<void>;
125
+ stop(): void;
126
+ ask(input: AskOwnerInput, caller: string): Promise<{
127
+ requestId: string;
128
+ expiresAt: string;
129
+ }>;
130
+ getAnswer(requestId: string, caller: string, waitSeconds: number): Promise<OwnerAnswer>;
131
+ cancel(requestId: string, caller: string): Promise<OwnerAnswer>;
132
+ /** Handle a `mobile_app_notification_action` event. Exposed for tests. */
133
+ handleActionEvent(event: ActionEvent): void;
134
+ private signRequest;
135
+ private verifyRequest;
136
+ private actionId;
137
+ private parseActionId;
138
+ private hmac;
139
+ private safeEqual;
140
+ private tagFor;
141
+ private assertOwner;
142
+ private settledAnswer;
143
+ private pendingAnswer;
144
+ private settle;
145
+ private wake;
146
+ private waitForOutcome;
147
+ private scheduleExpiry;
148
+ private replaceNotification;
149
+ private enforceRateLimits;
150
+ private reserve;
151
+ private release;
152
+ /**
153
+ * Periodic cleanup, independent of new activity: outcomes a day after their
154
+ * question expired (a caller polling that late sees "timeout"), labels of
155
+ * expired questions, and rate-limit entries that no longer count.
156
+ * Exposed for tests.
157
+ */
158
+ sweep(): void;
159
+ /** Sizes of the in-memory state, for tests and diagnostics. */
160
+ stateSize(): {
161
+ outcomes: number;
162
+ known: number;
163
+ open: number;
164
+ asked: number;
165
+ waiters: number;
166
+ };
167
+ }
@@ -0,0 +1,439 @@
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
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
30
+ import { logger } from '../utils/logger.js';
31
+ export const ACTION_EVENT = 'mobile_app_notification_action';
32
+ export const LIMITS = {
33
+ questionChars: 256,
34
+ titleChars: 60,
35
+ buttonChars: 20,
36
+ maxButtons: 3,
37
+ minTimeoutSeconds: 60,
38
+ maxTimeoutSeconds: 7 * 24 * 60 * 60,
39
+ defaultTimeoutSeconds: 600,
40
+ maxWaitSeconds: 50,
41
+ maxOpenPerCaller: 3,
42
+ maxPerCallerPerHour: 30,
43
+ };
44
+ const REQUEST_PREFIX = 'q1';
45
+ const ACTION_PREFIX = 'MCPASK';
46
+ /** How long the confirmation that replaces an answered question stays on the phone. */
47
+ const CONFIRMATION_SECONDS = 300;
48
+ /** Outcomes stay readable this long after their question expired. */
49
+ const OUTCOME_RETENTION_MS = 24 * 60 * 60 * 1000;
50
+ const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
51
+ const b64url = (buffer) => buffer.toString('base64url');
52
+ export class OwnerQuestionService {
53
+ deps;
54
+ key;
55
+ now;
56
+ /** Final outcomes by nonce, until the question's expiry passes. */
57
+ outcomes = new Map();
58
+ /** Open questions per caller sub: nonce -> expiry (ms). */
59
+ open = new Map();
60
+ /** Ask timestamps per caller sub, for the hourly cap. */
61
+ asked = new Map();
62
+ /** Pollers waiting for an outcome, by nonce. */
63
+ waiters = new Map();
64
+ /** Expiry timers by nonce (best effort: lost on restart; the phone also times out on its own). */
65
+ expiryTimers = new Map();
66
+ /** Labels and target of open questions, for nicer confirmations while the server stays up. */
67
+ known = new Map();
68
+ sweepTimer;
69
+ /** Why questions cannot be answered right now (Home Assistant refused the tap subscription). */
70
+ unavailable;
71
+ constructor(deps) {
72
+ this.deps = deps;
73
+ this.now = deps.now ?? Date.now;
74
+ if (deps.secret) {
75
+ this.key = createHmac('sha256', deps.secret).update('mcp-ha-connect/owner-questions/v1').digest();
76
+ }
77
+ else {
78
+ this.key = randomBytes(32);
79
+ logger.warn('Owner questions: no server secret configured; open questions will not survive a restart');
80
+ }
81
+ }
82
+ async start() {
83
+ await this.deps.subscribe(ACTION_EVENT, (event) => this.handleActionEvent(event), () => {
84
+ this.unavailable =
85
+ 'Home Assistant refused the subscription to notification taps (the server needs an admin Home Assistant token)';
86
+ logger.error(`Owner questions unavailable: ${this.unavailable}`);
87
+ });
88
+ this.sweepTimer = setInterval(() => this.sweep(), SWEEP_INTERVAL_MS);
89
+ this.sweepTimer.unref?.();
90
+ logger.info('Owner questions: listening for notification taps');
91
+ if (!this.deps.allowedUserIds?.length) {
92
+ logger.warn('Owner questions: any Home Assistant user can answer; set MCP_OWNER_QUESTIONS_HA_USERS to restrict it');
93
+ }
94
+ }
95
+ stop() {
96
+ clearInterval(this.sweepTimer);
97
+ for (const timer of this.expiryTimers.values())
98
+ clearTimeout(timer);
99
+ this.expiryTimers.clear();
100
+ }
101
+ async ask(input, caller) {
102
+ if (this.unavailable) {
103
+ throw new Error(`Owner questions are unavailable: ${this.unavailable}`);
104
+ }
105
+ const now = this.now();
106
+ this.enforceRateLimits(caller, now);
107
+ const nonce = b64url(randomBytes(16));
108
+ const expiresAtSec = Math.floor(now / 1000) + input.timeoutSeconds;
109
+ const payload = {
110
+ v: 1,
111
+ n: nonce,
112
+ s: caller,
113
+ t: input.target,
114
+ e: expiresAtSec,
115
+ b: input.buttons,
116
+ q: input.question,
117
+ ti: input.title,
118
+ };
119
+ const requestId = this.signRequest(payload);
120
+ const data = {
121
+ tag: this.tagFor(nonce),
122
+ actions: input.buttons.map((title, index) => ({
123
+ action: this.actionId(nonce, index, expiresAtSec, input.target),
124
+ title,
125
+ })),
126
+ // Stays until answered: not dismissed by tapping the body (sticky) or by
127
+ // swiping (persistent, needs the tag); the phone removes it at expiry.
128
+ sticky: true,
129
+ persistent: true,
130
+ priority: 'high',
131
+ ttl: 0,
132
+ timeout: input.timeoutSeconds,
133
+ };
134
+ if (input.channel)
135
+ data.channel = input.channel;
136
+ if (input.importance)
137
+ data.importance = input.importance;
138
+ // Reserve the slot before sending, so concurrent calls cannot all pass the limits.
139
+ this.reserve(caller, nonce, expiresAtSec * 1000, now);
140
+ try {
141
+ await this.deps.notify(input.target, { title: input.title, message: input.question, data });
142
+ }
143
+ catch {
144
+ // The underlying error can carry request details; neither the caller
145
+ // nor this log gets its text.
146
+ this.release(caller, nonce, now);
147
+ logger.warn('Owner questions: sending the notification failed', { target: input.target });
148
+ throw new Error(`Could not send the notification through Home Assistant (is '${input.target}' a valid notify target?)`);
149
+ }
150
+ this.known.set(nonce, { target: input.target, title: input.title, buttons: input.buttons, expiresAt: expiresAtSec * 1000 });
151
+ // Count from now, after delivery: the signed expiry is what matters.
152
+ this.scheduleExpiry(nonce, Math.max(expiresAtSec * 1000 - this.now(), 0));
153
+ logger.info('Owner question sent', { caller, target: input.target, buttons: input.buttons.length, expiresAt: expiresAtSec });
154
+ return { requestId, expiresAt: new Date(expiresAtSec * 1000).toISOString() };
155
+ }
156
+ async getAnswer(requestId, caller, waitSeconds) {
157
+ const payload = this.verifyRequest(requestId);
158
+ if (!payload) {
159
+ return { status: 'unknown', reason: 'Not a valid question id from this server (or the server secret changed)' };
160
+ }
161
+ this.assertOwner(payload, caller);
162
+ const settled = this.settledAnswer(payload);
163
+ if (settled || waitSeconds <= 0) {
164
+ return settled ?? this.pendingAnswer(payload);
165
+ }
166
+ const untilExpiry = payload.e * 1000 - this.now();
167
+ await this.waitForOutcome(payload.n, Math.min(waitSeconds * 1000, Math.max(untilExpiry, 0)));
168
+ return this.settledAnswer(payload) ?? this.pendingAnswer(payload);
169
+ }
170
+ async cancel(requestId, caller) {
171
+ const payload = this.verifyRequest(requestId);
172
+ if (!payload) {
173
+ return { status: 'unknown', reason: 'Not a valid question id from this server (or the server secret changed)' };
174
+ }
175
+ this.assertOwner(payload, caller);
176
+ const settled = this.settledAnswer(payload);
177
+ if (settled) {
178
+ return settled;
179
+ }
180
+ this.settle(payload.n, { status: 'cancelled', cancelledAt: this.now() }, payload.e * 1000);
181
+ await this.replaceNotification(payload.n, payload.t, payload.ti, 'Cancelled - no answer needed');
182
+ return this.settledAnswer(payload);
183
+ }
184
+ /** Handle a `mobile_app_notification_action` event. Exposed for tests. */
185
+ handleActionEvent(event) {
186
+ const parsed = this.parseActionId(event.data.action);
187
+ if (!parsed) {
188
+ return; // not one of ours
189
+ }
190
+ if (event.origin !== 'REMOTE' || !event.context.user_id) {
191
+ logger.warn('Owner questions: ignored a tap not coming from a mobile app', { origin: event.origin });
192
+ return;
193
+ }
194
+ if (this.deps.allowedUserIds?.length && !this.deps.allowedUserIds.includes(event.context.user_id)) {
195
+ logger.warn('Owner questions: ignored a tap from a Home Assistant user that may not answer');
196
+ return;
197
+ }
198
+ const { nonce, index, expiresAtSec, target } = parsed;
199
+ const known = this.known.get(nonce);
200
+ if (this.now() >= expiresAtSec * 1000) {
201
+ logger.info('Owner questions: ignored a tap after expiry');
202
+ void this.replaceNotification(nonce, target, known?.title ?? 'Question', 'Expired - the answer was not recorded');
203
+ return;
204
+ }
205
+ if (this.outcomes.has(nonce)) {
206
+ return; // first tap wins
207
+ }
208
+ this.settle(nonce, { status: 'answered', index, answeredAt: this.now(), answeredBy: event.context.user_id }, expiresAtSec * 1000);
209
+ logger.info('Owner question answered', { index });
210
+ const label = known?.buttons[index];
211
+ void this.replaceNotification(nonce, target, known?.title ?? 'Question', label ? `Answered: ${label}` : 'Answer recorded');
212
+ }
213
+ // ---- internals -------------------------------------------------------
214
+ signRequest(payload) {
215
+ const body = `${REQUEST_PREFIX}.${b64url(Buffer.from(JSON.stringify(payload), 'utf8'))}`;
216
+ return `${body}.${b64url(this.hmac(`request|${body}`))}`;
217
+ }
218
+ verifyRequest(requestId) {
219
+ const parts = typeof requestId === 'string' ? requestId.split('.') : [];
220
+ if (parts.length !== 3 || parts[0] !== REQUEST_PREFIX) {
221
+ return null;
222
+ }
223
+ const body = `${parts[0]}.${parts[1]}`;
224
+ if (!this.safeEqual(parts[2], b64url(this.hmac(`request|${body}`)))) {
225
+ return null;
226
+ }
227
+ try {
228
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
229
+ return payload.v === 1 ? payload : null;
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ }
235
+ actionId(nonce, index, expiresAtSec, target) {
236
+ const sig = b64url(this.hmac(`action|${nonce}|${index}|${expiresAtSec}|${target}`)).slice(0, 22);
237
+ return `${ACTION_PREFIX}.${nonce}.${index}.${expiresAtSec}.${target}.${sig}`;
238
+ }
239
+ parseActionId(action) {
240
+ if (typeof action !== 'string' || !action.startsWith(`${ACTION_PREFIX}.`)) {
241
+ return null;
242
+ }
243
+ 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);
244
+ if (!match) {
245
+ logger.warn('Owner questions: ignored a malformed action id');
246
+ return null;
247
+ }
248
+ const [, nonce, index, expires, target, sig] = match;
249
+ const expected = b64url(this.hmac(`action|${nonce}|${index}|${expires}|${target}`)).slice(0, 22);
250
+ if (!this.safeEqual(sig, expected)) {
251
+ logger.warn('Owner questions: ignored a tap with an invalid signature');
252
+ return null;
253
+ }
254
+ return { nonce, index: Number(index), expiresAtSec: Number(expires), target };
255
+ }
256
+ hmac(message) {
257
+ return createHmac('sha256', this.key).update(message).digest();
258
+ }
259
+ safeEqual(a, b) {
260
+ const left = Buffer.from(a);
261
+ const right = Buffer.from(b);
262
+ return left.length === right.length && timingSafeEqual(left, right);
263
+ }
264
+ tagFor(nonce) {
265
+ return `mcpask-${nonce}`;
266
+ }
267
+ assertOwner(payload, caller) {
268
+ if (payload.s !== caller) {
269
+ throw new Error('This question was asked by a different client');
270
+ }
271
+ }
272
+ settledAnswer(payload) {
273
+ const base = { question: payload.q, buttons: payload.b };
274
+ const outcome = this.outcomes.get(payload.n);
275
+ if (outcome?.status === 'answered') {
276
+ return {
277
+ status: 'answered',
278
+ index: outcome.index,
279
+ button: payload.b[outcome.index] ?? `#${outcome.index}`,
280
+ answeredAt: new Date(outcome.answeredAt).toISOString(),
281
+ answeredBy: outcome.answeredBy,
282
+ ...base,
283
+ };
284
+ }
285
+ if (outcome?.status === 'cancelled') {
286
+ return { status: 'cancelled', cancelledAt: new Date(outcome.cancelledAt).toISOString(), ...base };
287
+ }
288
+ if (this.now() >= payload.e * 1000) {
289
+ return { status: 'timeout', expiredAt: new Date(payload.e * 1000).toISOString(), ...base };
290
+ }
291
+ return null;
292
+ }
293
+ pendingAnswer(payload) {
294
+ return { status: 'pending', expiresAt: new Date(payload.e * 1000).toISOString(), question: payload.q, buttons: payload.b };
295
+ }
296
+ settle(nonce, outcome, expiresAtMs) {
297
+ this.outcomes.set(nonce, { ...outcome, expiresAt: expiresAtMs });
298
+ this.known.delete(nonce);
299
+ for (const questions of this.open.values()) {
300
+ questions.delete(nonce);
301
+ }
302
+ const timer = this.expiryTimers.get(nonce);
303
+ if (timer) {
304
+ clearTimeout(timer);
305
+ this.expiryTimers.delete(nonce);
306
+ }
307
+ this.wake(nonce);
308
+ }
309
+ wake(nonce) {
310
+ for (const resolve of this.waiters.get(nonce) ?? []) {
311
+ resolve();
312
+ }
313
+ this.waiters.delete(nonce);
314
+ }
315
+ waitForOutcome(nonce, ms) {
316
+ return new Promise((resolve) => {
317
+ const waiters = this.waiters.get(nonce) ?? new Set();
318
+ this.waiters.set(nonce, waiters);
319
+ const done = () => {
320
+ clearTimeout(timer);
321
+ waiters.delete(done);
322
+ if (waiters.size === 0 && this.waiters.get(nonce) === waiters) {
323
+ this.waiters.delete(nonce);
324
+ }
325
+ resolve();
326
+ };
327
+ const timer = setTimeout(done, ms);
328
+ waiters.add(done);
329
+ });
330
+ }
331
+ scheduleExpiry(nonce, ms) {
332
+ // Node timers overflow above ~24.8 days; questions last at most 7 days.
333
+ const timer = setTimeout(() => {
334
+ this.expiryTimers.delete(nonce);
335
+ if (this.outcomes.has(nonce)) {
336
+ return;
337
+ }
338
+ for (const questions of this.open.values()) {
339
+ questions.delete(nonce);
340
+ }
341
+ this.wake(nonce);
342
+ const known = this.known.get(nonce);
343
+ this.known.delete(nonce);
344
+ if (known) {
345
+ void this.replaceNotification(nonce, known.target, known.title, 'Expired - treated as no');
346
+ }
347
+ }, ms);
348
+ timer.unref?.();
349
+ this.expiryTimers.set(nonce, timer);
350
+ }
351
+ async replaceNotification(nonce, target, title, message) {
352
+ try {
353
+ // Same tag replaces the question; no actions, dismissible, gone after a while.
354
+ await this.deps.notify(target, {
355
+ title,
356
+ message,
357
+ data: { tag: this.tagFor(nonce), sticky: false, persistent: false, timeout: CONFIRMATION_SECONDS },
358
+ });
359
+ }
360
+ catch {
361
+ logger.warn('Owner questions: could not update the notification', { target });
362
+ }
363
+ }
364
+ enforceRateLimits(caller, now) {
365
+ const open = this.open.get(caller);
366
+ if (open) {
367
+ for (const [nonce, expiresAt] of open) {
368
+ if (expiresAt <= now)
369
+ open.delete(nonce);
370
+ }
371
+ if (open.size >= LIMITS.maxOpenPerCaller) {
372
+ throw new Error(`Too many open questions (${open.size}); answer, cancel or wait for one to expire first`);
373
+ }
374
+ }
375
+ const recent = (this.asked.get(caller) ?? []).filter((t) => t > now - 60 * 60 * 1000);
376
+ if (recent.length >= LIMITS.maxPerCallerPerHour) {
377
+ throw new Error(`Too many questions in the last hour (limit ${LIMITS.maxPerCallerPerHour})`);
378
+ }
379
+ this.asked.set(caller, recent);
380
+ }
381
+ reserve(caller, nonce, expiresAtMs, now) {
382
+ const open = this.open.get(caller) ?? new Map();
383
+ open.set(nonce, expiresAtMs);
384
+ this.open.set(caller, open);
385
+ const asked = this.asked.get(caller) ?? [];
386
+ asked.push(now);
387
+ this.asked.set(caller, asked);
388
+ }
389
+ release(caller, nonce, now) {
390
+ this.open.get(caller)?.delete(nonce);
391
+ const asked = this.asked.get(caller);
392
+ const index = asked?.lastIndexOf(now) ?? -1;
393
+ if (asked && index >= 0)
394
+ asked.splice(index, 1);
395
+ }
396
+ /**
397
+ * Periodic cleanup, independent of new activity: outcomes a day after their
398
+ * question expired (a caller polling that late sees "timeout"), labels of
399
+ * expired questions, and rate-limit entries that no longer count.
400
+ * Exposed for tests.
401
+ */
402
+ sweep() {
403
+ const now = this.now();
404
+ for (const [nonce, outcome] of this.outcomes) {
405
+ if (outcome.expiresAt + OUTCOME_RETENTION_MS < now)
406
+ this.outcomes.delete(nonce);
407
+ }
408
+ for (const [nonce, known] of this.known) {
409
+ if (known.expiresAt < now)
410
+ this.known.delete(nonce);
411
+ }
412
+ for (const [caller, open] of this.open) {
413
+ for (const [nonce, expiresAt] of open) {
414
+ if (expiresAt <= now)
415
+ open.delete(nonce);
416
+ }
417
+ if (open.size === 0)
418
+ this.open.delete(caller);
419
+ }
420
+ for (const [caller, asked] of this.asked) {
421
+ const recent = asked.filter((t) => t > now - 60 * 60 * 1000);
422
+ if (recent.length === 0)
423
+ this.asked.delete(caller);
424
+ else
425
+ this.asked.set(caller, recent);
426
+ }
427
+ }
428
+ /** Sizes of the in-memory state, for tests and diagnostics. */
429
+ stateSize() {
430
+ return {
431
+ outcomes: this.outcomes.size,
432
+ known: this.known.size,
433
+ open: this.open.size,
434
+ asked: this.asked.size,
435
+ waiters: this.waiters.size,
436
+ };
437
+ }
438
+ }
439
+ //# sourceMappingURL=service.js.map