@coffeerunhobby/mcp-ha-connect 2.1.1 → 2.2.1

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 (106) hide show
  1. package/README.md +23 -5
  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/client.d.ts +33 -1
  18. package/dist/omadaClient/client.js +61 -2
  19. package/dist/omadaClient/client.js.map +1 -1
  20. package/dist/omadaClient/index.d.ts +7 -0
  21. package/dist/omadaClient/index.js +6 -0
  22. package/dist/omadaClient/index.js.map +1 -1
  23. package/dist/omadaClient/request.d.ts +5 -0
  24. package/dist/omadaClient/request.js +11 -2
  25. package/dist/omadaClient/request.js.map +1 -1
  26. package/dist/ownerQuestions/service.d.ts +167 -0
  27. package/dist/ownerQuestions/service.js +439 -0
  28. package/dist/ownerQuestions/service.js.map +1 -0
  29. package/dist/server/common.d.ts +3 -0
  30. package/dist/server/common.js +2 -1
  31. package/dist/server/common.js.map +1 -1
  32. package/dist/server/http.js +30 -6
  33. package/dist/server/http.js.map +1 -1
  34. package/dist/server/stream.d.ts +2 -0
  35. package/dist/server/stream.js +2 -1
  36. package/dist/server/stream.js.map +1 -1
  37. package/dist/tools/common.d.ts +1 -1
  38. package/dist/tools/common.js +9 -2
  39. package/dist/tools/common.js.map +1 -1
  40. package/dist/tools/homeassistant/askOwner.d.ts +29 -0
  41. package/dist/tools/homeassistant/askOwner.js +85 -0
  42. package/dist/tools/homeassistant/askOwner.js.map +1 -0
  43. package/dist/tools/homeassistant/getAutomationTrace.d.ts +5 -0
  44. package/dist/tools/homeassistant/getAutomationTrace.js +10 -5
  45. package/dist/tools/homeassistant/getAutomationTrace.js.map +1 -1
  46. package/dist/tools/index.d.ts +3 -0
  47. package/dist/tools/index.js +5 -1
  48. package/dist/tools/index.js.map +1 -1
  49. package/dist/tools/omada/blockClient.js +3 -1
  50. package/dist/tools/omada/blockClient.js.map +1 -1
  51. package/dist/tools/omada/deleteClient.d.ts +3 -0
  52. package/dist/tools/omada/deleteClient.js +15 -0
  53. package/dist/tools/omada/deleteClient.js.map +1 -0
  54. package/dist/tools/omada/index.js +7 -2
  55. package/dist/tools/omada/index.js.map +1 -1
  56. package/dist/tools/omada/listBlockedClients.d.ts +3 -0
  57. package/dist/tools/omada/listBlockedClients.js +9 -0
  58. package/dist/tools/omada/listBlockedClients.js.map +1 -0
  59. package/dist/tools/omada/namespace.js +17 -0
  60. package/dist/tools/omada/namespace.js.map +1 -1
  61. package/dist/utils/plainText.d.ts +22 -0
  62. package/dist/utils/plainText.js +39 -0
  63. package/dist/utils/plainText.js.map +1 -0
  64. package/dist/utils/redact.d.ts +21 -0
  65. package/dist/utils/redact.js +53 -0
  66. package/dist/utils/redact.js.map +1 -0
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +1 -1
  69. package/docs/CHANGELOG.md +24 -0
  70. package/openapi.json +1 -1
  71. package/package.json +1 -1
  72. package/src/config.ts +10 -0
  73. package/src/haClient/automations.ts +39 -7
  74. package/src/haClient/events.ts +289 -56
  75. package/src/haClient/index.ts +10 -4
  76. package/src/haClient/wsCommand.ts +44 -0
  77. package/src/omadaClient/client.ts +82 -4
  78. package/src/omadaClient/index.ts +9 -1
  79. package/src/omadaClient/request.ts +13 -2
  80. package/src/ownerQuestions/service.ts +536 -0
  81. package/src/server/common.ts +5 -1
  82. package/src/server/http.ts +30 -6
  83. package/src/server/stream.ts +4 -1
  84. package/src/tools/common.ts +9 -2
  85. package/src/tools/homeassistant/askOwner.ts +133 -0
  86. package/src/tools/homeassistant/getAutomationTrace.ts +13 -7
  87. package/src/tools/index.ts +8 -1
  88. package/src/tools/omada/blockClient.ts +3 -1
  89. package/src/tools/omada/deleteClient.ts +27 -0
  90. package/src/tools/omada/index.ts +7 -2
  91. package/src/tools/omada/listBlockedClients.ts +17 -0
  92. package/src/tools/omada/namespace.ts +19 -0
  93. package/src/utils/plainText.ts +48 -0
  94. package/src/utils/redact.ts +59 -0
  95. package/src/version.ts +1 -1
  96. package/tests/config.test.ts +12 -0
  97. package/tests/haClient/automationTrace.test.ts +59 -0
  98. package/tests/haClient/automations.test.ts +16 -0
  99. package/tests/haClient/events.test.ts +455 -0
  100. package/tests/haClient/eventsTls.test.ts +52 -0
  101. package/tests/omadaClient/clientBlocks.test.ts +170 -0
  102. package/tests/ownerQuestions/service.test.ts +499 -0
  103. package/tests/ownerQuestions/tools.test.ts +186 -0
  104. package/tests/tools/homeassistant/handlers.test.ts +10 -1
  105. package/tests/tools/omada/graph.test.ts +13 -2
  106. package/tests/utils/redact.test.ts +105 -0
@@ -0,0 +1,186 @@
1
+ /**
2
+ * askOwner / getOwnerAnswer / cancelOwnerQuestion tools: input validation,
3
+ * RBAC, caller binding, log redaction, and a real MCP round trip.
4
+ */
5
+
6
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
+ import type { McpServer } from '@modelcontextprotocol/server';
8
+ import { Client, InMemoryTransport } from '@modelcontextprotocol/client';
9
+
10
+ import { OwnerQuestionService } from '../../src/ownerQuestions/service.js';
11
+ import { registerOwnerQuestionTools, askOwnerSchema } from '../../src/tools/homeassistant/askOwner.js';
12
+ import { createServer } from '../../src/server/common.js';
13
+ import { Permission, Role } from '../../src/permissions/index.js';
14
+ import { setLocalFullTrust } from '../../src/tools/common.js';
15
+ import { logger } from '../../src/utils/logger.js';
16
+
17
+ type Handler = (args: unknown, extra: unknown) => Promise<{ content: { text: string }[]; isError?: boolean }>;
18
+
19
+ function createMockServer() {
20
+ const handlers = new Map<string, Handler>();
21
+ return {
22
+ registerTool: vi.fn((name: string, _config: unknown, handler: Handler) => handlers.set(name, handler)),
23
+ handlers,
24
+ } as unknown as McpServer & { handlers: Map<string, Handler> };
25
+ }
26
+
27
+ const extraFor = (sub: string, permissions: number) => ({
28
+ sessionId: 's',
29
+ http: { authInfo: { token: '', clientId: sub, scopes: [], extra: { permissions } } },
30
+ });
31
+
32
+ const parse = (result: { content: { text: string }[] }) => JSON.parse(result.content[0].text) as Record<string, unknown>;
33
+
34
+ const valid = { question: 'Aprinzi lumina în baie?', target: 'mobile_app_phone_user5' };
35
+
36
+ function makeService() {
37
+ const notify = vi.fn().mockResolvedValue([]);
38
+ const service = new OwnerQuestionService({ notify, subscribe: vi.fn().mockResolvedValue('s'), secret: 'k'.repeat(40) });
39
+ return { service, notify };
40
+ }
41
+
42
+ describe('askOwner input validation', () => {
43
+ it('accepts plain text including Romanian diacritics, and applies defaults', () => {
44
+ const parsed = askOwnerSchema.parse(valid);
45
+ expect(parsed.question).toBe('Aprinzi lumina în baie?');
46
+ expect(parsed.buttons).toBeUndefined();
47
+ });
48
+
49
+ it('NFC-normalizes text (a decomposed ș becomes one character)', () => {
50
+ expect(askOwnerSchema.parse({ ...valid, question: 'ș?' }).question).toBe('ș?');
51
+ });
52
+
53
+ it.each([
54
+ ['an emoji', { question: 'Approve? 👍' }, /U\+1F44D/],
55
+ ['a zero-width joiner', { question: 'ok‍ok' }, /U\+200D/],
56
+ ['a right-to-left override', { question: 'pay ‮evil' }, /U\+202E/],
57
+ ['stacked combining marks', { question: 'á́' }, /U\+0301/],
58
+ ['a 257-character question', { question: 'x'.repeat(257) }, /257 characters; the maximum is 256/],
59
+ ['a line break in the title', { title: 'two\nlines' }, /title contains a disallowed character U\+000A/],
60
+ ['a 61-character title', { title: 't'.repeat(61) }, /maximum is 60/],
61
+ ['an emoji button', { buttons: ['Yes ✅', 'No'] }, /button label/],
62
+ ['four buttons', { buttons: ['a', 'b', 'c', 'd'] }, /3/],
63
+ ['duplicate buttons', { buttons: ['Yes', 'yes'] }, /unique/],
64
+ ['a non-mobile target', { target: 'persistent_notification' }, /mobile app notify service/],
65
+ ['a timeout over 7 days', { timeoutSeconds: 7 * 24 * 3600 + 1 }, /604800/],
66
+ ['a timeout under a minute', { timeoutSeconds: 59 }, /60/],
67
+ ])('refuses %s', (_name, overrides, error) => {
68
+ const result = askOwnerSchema.safeParse({ ...valid, ...overrides });
69
+ expect(result.success).toBe(false);
70
+ expect(JSON.stringify(result.error!.issues)).toMatch(error);
71
+ });
72
+
73
+ it('accepts a 256-character question with line breaks', () => {
74
+ const question = `${'x'.repeat(100)}\n${'y'.repeat(155)}`;
75
+ expect(askOwnerSchema.parse({ ...valid, question }).question).toBe(question);
76
+ });
77
+ });
78
+
79
+ describe('owner question tools', () => {
80
+ let server: ReturnType<typeof createMockServer>;
81
+ let service: OwnerQuestionService;
82
+ let notify: ReturnType<typeof vi.fn>;
83
+
84
+ beforeEach(() => {
85
+ server = createMockServer();
86
+ ({ service, notify } = makeService());
87
+ registerOwnerQuestionTools(server, service);
88
+ });
89
+
90
+ it('registers askOwner, getOwnerAnswer and cancelOwnerQuestion', () => {
91
+ expect([...server.handlers.keys()]).toEqual(['askOwner', 'getOwnerAnswer', 'cancelOwnerQuestion']);
92
+ });
93
+
94
+ it.each(['askOwner', 'getOwnerAnswer', 'cancelOwnerQuestion'])('%s requires NOTIFY', async (tool) => {
95
+ const result = await server.handlers.get(tool)!({ ...valid, requestId: 'x' }, extraFor('reader', Role.READONLY));
96
+ expect(parse(result)).toMatchObject({ error: 'Permission denied' });
97
+ expect(String(parse(result).message)).toContain('NOTIFY');
98
+ expect(notify).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('askOwner applies the default title, buttons and timeout', async () => {
102
+ const result = await server.handlers.get('askOwner')!(valid, extraFor('approver', Permission.NOTIFY));
103
+
104
+ expect(parse(result)).toHaveProperty('requestId');
105
+ expect(notify.mock.calls[0][1]).toMatchObject({ title: 'Approval needed', data: { timeout: 600 } });
106
+ expect(notify.mock.calls[0][1].data.actions.map((a: { title: string }) => a.title)).toEqual(['Approve', 'Deny']);
107
+ });
108
+
109
+ it('binds the question to the asking token sub', async () => {
110
+ const asked = parse(await server.handlers.get('askOwner')!(valid, extraFor('approver', Permission.NOTIFY)));
111
+
112
+ const own = await server.handlers.get('getOwnerAnswer')!({ requestId: asked.requestId, waitSeconds: 0 }, extraFor('approver', Permission.NOTIFY));
113
+ const other = await server.handlers.get('getOwnerAnswer')!({ requestId: asked.requestId, waitSeconds: 0 }, extraFor('harvey', Permission.NOTIFY));
114
+
115
+ expect(parse(own)).toMatchObject({ status: 'pending' });
116
+ expect(other.isError).toBe(true);
117
+ expect(String(parse(other).message)).toMatch(/different client/);
118
+ });
119
+
120
+ it('logs tool arguments (the question text) at debug level only', async () => {
121
+ const info = vi.spyOn(logger, 'info');
122
+ const debug = vi.spyOn(logger, 'debug');
123
+ try {
124
+ await server.handlers.get('askOwner')!(
125
+ { ...valid, question: 'Secret plan: unlock the front door?' },
126
+ extraFor('approver', Permission.NOTIFY)
127
+ );
128
+ expect(JSON.stringify(info.mock.calls)).not.toContain('unlock the front door');
129
+ expect(JSON.stringify(info.mock.calls)).toContain('Tool invoked');
130
+ expect(JSON.stringify(debug.mock.calls)).toContain('unlock the front door');
131
+ } finally {
132
+ info.mockRestore();
133
+ debug.mockRestore();
134
+ }
135
+ });
136
+ });
137
+
138
+ describe('owner question tools over MCP', () => {
139
+ beforeEach(() => setLocalFullTrust(true));
140
+ afterEach(() => setLocalFullTrust(false));
141
+
142
+ it('are listed with a JSON Schema and callable end to end', async () => {
143
+ const { service, notify } = makeService();
144
+ const server = createServer({ haClient: {} as never, ownerQuestions: service });
145
+ const client = new Client({ name: 'ask-owner-test', version: '0' });
146
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
147
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
148
+ try {
149
+ const { tools } = await client.listTools();
150
+ const askOwner = tools.find((t) => t.name === 'askOwner');
151
+ expect(askOwner?.inputSchema.required).toEqual(['question', 'target']);
152
+ expect(tools.map((t) => t.name)).toEqual(expect.arrayContaining(['getOwnerAnswer', 'cancelOwnerQuestion']));
153
+
154
+ const asked = await client.callTool({ name: 'askOwner', arguments: { ...valid, buttons: ['Da', 'Nu'] } });
155
+ const { requestId } = JSON.parse((asked.content as Array<{ text: string }>)[0].text);
156
+ expect(notify).toHaveBeenCalledTimes(1);
157
+
158
+ const answer = await client.callTool({ name: 'getOwnerAnswer', arguments: { requestId, waitSeconds: 0 } });
159
+ expect(JSON.parse((answer.content as Array<{ text: string }>)[0].text)).toMatchObject({
160
+ status: 'pending',
161
+ buttons: ['Da', 'Nu'],
162
+ });
163
+
164
+ const refused = await client.callTool({ name: 'askOwner', arguments: { ...valid, question: 'ok 👍' } });
165
+ expect(refused.isError).toBe(true);
166
+ expect(notify).toHaveBeenCalledTimes(1);
167
+ } finally {
168
+ await client.close();
169
+ await server.close();
170
+ }
171
+ });
172
+
173
+ it('are not registered when no owner question service is running', async () => {
174
+ const server = createServer({ haClient: {} as never });
175
+ const client = new Client({ name: 'ask-owner-test', version: '0' });
176
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
177
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
178
+ try {
179
+ const { tools } = await client.listTools();
180
+ expect(tools.map((t) => t.name)).not.toContain('askOwner');
181
+ } finally {
182
+ await client.close();
183
+ await server.close();
184
+ }
185
+ });
186
+ });
@@ -551,9 +551,18 @@ describe('HomeAssistant Tool Handlers', () => {
551
551
  const handler = server.getHandler('getAutomationTrace')!;
552
552
  const result = await handler({ entity_id: 'automation.test' }, mockExtra);
553
553
 
554
- expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test');
554
+ expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test', undefined);
555
555
  expect(result.content[0].text).toContain('trace_count');
556
556
  });
557
+
558
+ it('getAutomationTrace forwards limit', async () => {
559
+ mockClient.getAutomationTrace.mockResolvedValue([]);
560
+ registerGetAutomationTraceTool(server as any, mockClient as any);
561
+
562
+ await server.getHandler('getAutomationTrace')!({ entity_id: 'automation.test', limit: 3 }, mockExtra);
563
+
564
+ expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test', 3);
565
+ });
557
566
  });
558
567
 
559
568
  describe('automation controls', () => {
@@ -79,11 +79,11 @@ describe('Omada graph tools - registration', () => {
79
79
  expect(server.handlers.has('omada_read')).toBe(true);
80
80
  });
81
81
 
82
- it('graph mode registers browse + read + 8 typed writes, and NO typed getters', () => {
82
+ it('graph mode registers browse + read + 9 typed writes, and NO typed getters', () => {
83
83
  const server = createMockServer();
84
84
  const client = createMockClient();
85
85
  const count = registerOmadaTools(server, client, 'graph');
86
- expect(count).toBe(10);
86
+ expect(count).toBe(11);
87
87
  const names = [...server.handlers.keys()];
88
88
  expect(names).toContain('omada_browse');
89
89
  expect(names).toContain('omada_read');
@@ -93,10 +93,12 @@ describe('Omada graph tools - registration', () => {
93
93
  expect(names).toContain('omada_cyclePoePort');
94
94
  expect(names).toContain('omada_setSsidEnabled');
95
95
  expect(names).toContain('omada_setSiteNtpServers');
96
+ expect(names).toContain('omada_deleteClient');
96
97
  // Typed read getters must NOT be present in graph mode.
97
98
  expect(names).not.toContain('omada_listSites');
98
99
  expect(names).not.toContain('omada_getFirewallSetting');
99
100
  expect(names).not.toContain('omada_getSiteNtpStatus');
101
+ expect(names).not.toContain('omada_listBlockedClients');
100
102
  });
101
103
 
102
104
  it('eager mode (default) registers the typed getters, not the graph tools', () => {
@@ -310,6 +312,15 @@ describe('omada_read', () => {
310
312
  expect(client.getSiteNtpStatus).not.toHaveBeenCalled();
311
313
  });
312
314
 
315
+ it('reads /clients/known as one page of known clients (with block state)', async () => {
316
+ (client.readResource as ReturnType<typeof vi.fn>).mockResolvedValue({ totalRows: 1, data: [{ mac: 'AA', block: true }] });
317
+ await read({ path: '/clients/known', page: 3, pageSize: 20, siteId: 'site1' }, readonlyExtra);
318
+ expect(client.readResource).toHaveBeenCalledTimes(1);
319
+ expect(client.readResource).toHaveBeenCalledWith(
320
+ expect.objectContaining({ pathTemplate: '/sites/{siteId}/insight/clients', siteId: 'site1', paginated: true, page: 3, pageSize: 20 })
321
+ );
322
+ });
323
+
313
324
  it('enforces per-path permission (fail closed) for under-privileged callers', async () => {
314
325
  const { isError, data } = parseResult(await read({ path: '/sites' }, noPermsExtra));
315
326
  expect(isError).toBe(true);
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Secrets returned by Home Assistant / Omada never reach a tool response.
3
+ */
4
+
5
+ import { describe, it, expect, vi } from 'vitest';
6
+ import type { McpServer } from '@modelcontextprotocol/server';
7
+
8
+ import { redactSecrets, REDACTED } from '../../src/utils/redact.js';
9
+ import { toToolResult } from '../../src/tools/common.js';
10
+ import { registerOmadaGraphTools } from '../../src/tools/omada/graph.js';
11
+ import type { OmadaClient } from '../../src/omadaClient/index.js';
12
+
13
+ /** Shape of an Omada SSID detail (GET .../wlans/{wlanId}/ssids/{ssidId}). */
14
+ const ssidDetail = {
15
+ ssidId: 'node-s55',
16
+ name: 'node-s55',
17
+ security: 3,
18
+ hidePwd: true,
19
+ pskSetting: { versionPsk: 2, encryptionPsk: 3, gikRekeyPskEnable: false, securityKey: 'HouseWifiPassw0rd!' },
20
+ macFilterEnable: false,
21
+ };
22
+
23
+ describe('redactSecrets', () => {
24
+ it('redacts the Wi-Fi password but keeps flags and numbers with similar names', () => {
25
+ const out = redactSecrets(ssidDetail);
26
+
27
+ expect(out.pskSetting.securityKey).toBe(REDACTED);
28
+ expect(out.pskSetting.versionPsk).toBe(2);
29
+ expect(out.pskSetting.encryptionPsk).toBe(3);
30
+ expect(out.hidePwd).toBe(true);
31
+ expect(out.name).toBe('node-s55');
32
+ expect(JSON.stringify(out)).not.toContain('HouseWifiPassw0rd!');
33
+ });
34
+
35
+ it.each([
36
+ ['RADIUS profile', { authServer: [{ ip: '192.168.0.2', port: 1812, secret: 'radius-s3cret' }], accountingServerPwd: 'acct-pw', coaPassword: 'coa-pw', radiusPwd: 'rp' }],
37
+ ['PPSK profile', { name: 'kids', ppsk: [{ name: 'tablet', password: 'ppsk-key-1', vlanId: 20 }] }],
38
+ ['VPN', { preSharedKey: 'ipsec-psk', presharedKey: 'wg-psk', privateKey: 'wg-private', publicKey: 'wg-public' }],
39
+ ['SNMP', { snmpV1V2CEnable: true, communityString: 'snmp-community' }],
40
+ ['portal and hotspot', { password: 'portal-pw', authCode: 'auth-code-123', simpleKey: 'sk', md5Key: 'mk' }],
41
+ ['SSID variants', { psk: 'override-psk', ssidPassword: 'ssid-pw', bridgeSsidPassword: 'bridge-pw', overrideSsidPassword: 'ov-pw' }],
42
+ ['VRRP and certificates', { key: 'vrrp-key', keyPassword: 'ks-pw', trustPassword: 'trust-pw' }],
43
+ ['webhooks and tokens', { shardedSecret: 'hook-secret', authToken: 'twilio-token', accessToken: 'at', token: 'user-token' }],
44
+ ])('redacts every secret in a %s', (_name, input) => {
45
+ const text = JSON.stringify(redactSecrets(input));
46
+
47
+ for (const secret of ['radius-s3cret', 'acct-pw', 'coa-pw', 'ppsk-key-1', 'ipsec-psk', 'wg-psk', 'wg-private', 'snmp-community', 'portal-pw', 'auth-code-123', 'override-psk', 'ssid-pw', 'bridge-pw', 'ov-pw', 'vrrp-key', 'ks-pw', 'trust-pw', 'hook-secret', 'twilio-token', 'user-token']) {
48
+ expect(text).not.toContain(secret);
49
+ }
50
+ });
51
+
52
+ it('keeps public, non-secret values (public keys, ids, names)', () => {
53
+ const out = redactSecrets({ publicKey: 'wg-public', keyId: 'k1', searchKey: 'abc', ppskProfileId: 'p1' });
54
+ expect(out).toEqual({ publicKey: 'wg-public', keyId: 'k1', searchKey: 'abc', ppskProfileId: 'p1' });
55
+ });
56
+
57
+ it('masks tokens inside URLs (Home Assistant camera image)', () => {
58
+ const out = redactSecrets({
59
+ entity_picture: '/api/camera_proxy/camera.door?token=0123456789abcdef&width=640',
60
+ attributes: { access_token: 'cam-token' },
61
+ });
62
+ expect(out.entity_picture).toBe(`/api/camera_proxy/camera.door?token=${REDACTED}&width=640`);
63
+ expect(out.attributes.access_token).toBe(REDACTED);
64
+ });
65
+
66
+ it('leaves empty secrets empty, so "is it set?" stays answerable', () => {
67
+ expect(redactSecrets({ password: '', securityKey: 'x' })).toEqual({ password: '', securityKey: REDACTED });
68
+ });
69
+
70
+ it('does not modify its input', () => {
71
+ const input = structuredClone(ssidDetail);
72
+ redactSecrets(input);
73
+ expect(input).toEqual(ssidDetail);
74
+ });
75
+
76
+ it('handles arrays, nulls and plain strings', () => {
77
+ expect(redactSecrets([{ password: 'p' }, null, 3])).toEqual([{ password: REDACTED }, null, 3]);
78
+ expect(redactSecrets('see /x?token=abc')).toBe(`see /x?token=${REDACTED}`);
79
+ expect(redactSecrets(null)).toBeNull();
80
+ });
81
+ });
82
+
83
+ describe('tool responses are redacted', () => {
84
+ it('toToolResult never carries a secret', () => {
85
+ const result = toToolResult(ssidDetail);
86
+ expect(result.content[0].text).not.toContain('HouseWifiPassw0rd!');
87
+ expect(result.content[0].text).toContain(REDACTED);
88
+ });
89
+
90
+ it('omada_read /wifi/ssids (SSID detail) does not return the Wi-Fi password', async () => {
91
+ const handlers = new Map<string, (args: unknown, extra: unknown) => Promise<{ content: { text: string }[] }>>();
92
+ const server = { registerTool: vi.fn((name, _c, h) => handlers.set(name, h)) } as unknown as McpServer;
93
+ const client = { getSsidDetail: vi.fn().mockResolvedValue(ssidDetail), getSsidList: vi.fn() } as unknown as OmadaClient;
94
+ registerOmadaGraphTools(server, client);
95
+
96
+ const result = await handlers.get('omada_read')!(
97
+ { path: '/wifi/ssids', params: { wlanId: 'w1', ssidId: 'node-s55' } },
98
+ { sessionId: 's', http: { authInfo: { extra: { permissions: 0xff } } } }
99
+ );
100
+
101
+ expect(client.getSsidDetail).toHaveBeenCalled();
102
+ expect(result.content[0].text).not.toContain('HouseWifiPassw0rd!');
103
+ expect(JSON.parse(result.content[0].text).pskSetting.securityKey).toBe(REDACTED);
104
+ });
105
+ });