-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathnativeMessaging.test.js
More file actions
201 lines (173 loc) · 6.2 KB
/
Copy pathnativeMessaging.test.js
File metadata and controls
201 lines (173 loc) · 6.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Mock dependencies before importing the module under test
jest.mock('./nativeMessagingProtocol', () => ({
isWrappedMessage: jest.fn(),
unwrapMessage: jest.fn(),
wrapMessage: jest.fn()
}))
jest.mock('../shared/constants/nativeMessaging', () => {
const actual = jest.requireActual('../shared/constants/nativeMessaging')
return {
...actual,
// Use shorter timeouts in tests so we can advance fake timers quickly.
REQUEST_TIMEOUT: {
...actual.REQUEST_TIMEOUT,
DEFAULT_MS: 1000,
AVAILABILITY_CHECK_MS: 500
},
// Make debug logging deterministic and set a simple host name.
NATIVE_MESSAGING_CONFIG: {
...actual.NATIVE_MESSAGING_CONFIG,
DEBUG_MODE: true,
LOG_PREFIX: '[NATIVE] ',
HOST_NAME: 'test-host'
}
}
})
const { NATIVE_MESSAGE_TYPES } = require('../shared/constants/nativeMessaging')
jest.mock('../shared/utils/logger', () => ({
logger: {
log: jest.fn(),
error: jest.fn()
}
}))
jest.mock('../shared/constants/auth', () => ({
AUTH_ERROR_PATTERNS: {
MASTER_PASSWORD_REQUIRED: 'MasterPasswordRequired',
MASTER_PASSWORD_INVALID: 'MasterPasswordInvalid'
}
}))
// Provide a fake runtime for testing
jest.mock('../shared/utils/runtime', () => ({
runtime: {
connectNative: jest.fn(),
lastError: null,
sendMessage: jest.fn(() => Promise.resolve()),
onMessage: { addListener: jest.fn() },
onDisconnect: { addListener: jest.fn() }
}
}))
describe('NativeMessaging & integration', () => {
let nativeModule
let runtime
beforeEach(() => {
// Reset modules to apply fresh mocks
jest.resetModules()
// Get fresh runtime mock
runtime = require('../shared/utils/runtime').runtime
// Clear runtime mocks
runtime.connectNative.mockReset()
runtime.sendMessage.mockClear()
runtime.lastError = null
// Import after mocks
nativeModule = require('./nativeMessaging')
})
test('connect() should call runtime.connectNative and resolve when not already connected', async () => {
const fakePort = {
onMessage: { addListener: jest.fn() },
onDisconnect: { addListener: jest.fn() }
}
runtime.connectNative.mockReturnValue(fakePort)
await expect(
nativeModule.nativeMessaging.connect()
).resolves.toBeUndefined()
expect(runtime.connectNative).toHaveBeenCalledWith('test-host')
expect(fakePort.onMessage.addListener).toHaveBeenCalled()
expect(fakePort.onDisconnect.addListener).toHaveBeenCalled()
})
test('connect() when already connected should resolve immediately without reconnecting', async () => {
const fakePort = {
onMessage: { addListener: jest.fn() },
onDisconnect: { addListener: jest.fn() }
}
runtime.connectNative.mockReturnValue(fakePort)
// First connect
await nativeModule.nativeMessaging.connect()
// Clear the mock and call again
runtime.connectNative.mockClear()
await expect(
nativeModule.nativeMessaging.connect()
).resolves.toBeUndefined()
expect(runtime.connectNative).not.toHaveBeenCalled()
})
test('sendRequest() should wrap and post message and resolve on response', async () => {
// Arrange
const { nativeMessaging } = nativeModule
const {
wrapMessage,
isWrappedMessage,
unwrapMessage
} = require('./nativeMessagingProtocol')
wrapMessage.mockImplementation((req) => ({ wrapped: req }))
// Simulate connected state
const fakePort = {
postMessage: jest.fn(),
onMessage: { addListener: jest.fn() },
onDisconnect: { addListener: jest.fn() }
}
runtime.connectNative.mockReturnValue(fakePort)
await nativeMessaging.connect()
// Grab registered listener
const messageListener = fakePort.onMessage.addListener.mock.calls[0][0]
// Act: send a request
const promise = nativeMessaging.sendRequest('TEST_CMD', { foo: 'bar' })
// Wrap internals: simulate incoming message
const responseMsg = { id: 1, result: { success: true }, success: true }
const wrappedResponse = { wrapped: responseMsg }
// isWrappedMessage -> true, unwrapMessage returns actual
isWrappedMessage.mockReturnValue(true)
unwrapMessage.mockReturnValue(responseMsg)
// Simulate message event
messageListener(wrappedResponse)
// Assert
await expect(promise).resolves.toEqual({ success: true })
expect(fakePort.postMessage).toHaveBeenCalledWith({
wrapped: { id: 1, command: 'TEST_CMD', params: { foo: 'bar' } }
})
})
test('sendRequest() should reject on timeout', async () => {
jest.useFakeTimers()
const { nativeMessaging } = nativeModule
// Simulate connected state
const fakePort = {
postMessage: jest.fn(),
onMessage: { addListener: jest.fn() },
onDisconnect: { addListener: jest.fn() }
}
runtime.connectNative.mockReturnValue(fakePort)
await nativeMessaging.connect()
const promise = nativeMessaging.sendRequest('OTHER_CMD')
// Advance time past default timeout (1000ms)
jest.advanceTimersByTime(1500)
await expect(promise).rejects.toThrow('Request timeout: OTHER_CMD')
jest.useRealTimers()
})
test('handleRequest does not clear session (secureChannel handles it)', async () => {
const secureChannel = require('./secureChannel')
// Message listener should be registered
expect(runtime.onMessage.addListener).toHaveBeenCalled()
// Replace secureChannel.ensureSession to simulate auth failure
secureChannel.secureChannel.ensureSession = jest
.fn()
.mockRejectedValue(new Error('MasterPasswordRequired: please unlock'))
secureChannel.secureChannel.secureRequest = jest.fn()
secureChannel.secureChannel.clearSession = jest.fn()
const messageListener = runtime.onMessage.addListener.mock.calls[0][0]
await new Promise((resolve) => {
messageListener(
{
type: NATIVE_MESSAGE_TYPES.REQUEST,
command: 'securedCommand',
params: {}
},
{},
(response) => {
expect(response.success).toBe(false)
expect(response.code).toBeDefined()
resolve(null)
}
)
})
// handleRequest never calls clearSession - secureChannel handles it
expect(secureChannel.secureChannel.clearSession).not.toHaveBeenCalled()
})
})