-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathnativeMessaging.js
More file actions
385 lines (336 loc) · 10.2 KB
/
Copy pathnativeMessaging.js
File metadata and controls
385 lines (336 loc) · 10.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import {
isWrappedMessage,
unwrapMessage,
wrapMessage
} from './nativeMessagingProtocol'
import { secureChannel } from './secureChannel'
import { AUTH_ERROR_PATTERNS } from '../shared/constants/auth'
import {
NATIVE_MESSAGE_TYPES,
NATIVE_MESSAGING_CONFIG,
NATIVE_MESSAGING_ERRORS,
REQUEST_TIMEOUT,
SPECIAL_COMMANDS,
SESSION_ERROR_PATTERNS,
SECURITY_ERROR_PATTERNS,
ERROR_CODES,
DISCONNECTION_ERROR_MESSAGES,
DESKTOP_APP_STATUS
} from '../shared/constants/nativeMessaging'
import { logger } from '../shared/utils/logger'
import { runtime } from '../shared/utils/runtime'
const createError = (message) => new Error(message)
const createTimeoutError = (command) =>
createError(`${NATIVE_MESSAGING_ERRORS.REQUEST_TIMEOUT}: ${command}`)
const createDisconnectionError = (lastError) =>
createError(lastError?.message || NATIVE_MESSAGING_ERRORS.DISCONNECTED)
const log = (...args) => {
if (NATIVE_MESSAGING_CONFIG.DEBUG_MODE) {
logger.log(NATIVE_MESSAGING_CONFIG.LOG_PREFIX, ...args)
}
}
const logError = (...args) =>
logger.error(NATIVE_MESSAGING_CONFIG.LOG_PREFIX, ...args)
const getTimeoutForCommand = (command) => {
switch (command) {
case SPECIAL_COMMANDS.CHECK_AVAILABILITY:
return REQUEST_TIMEOUT.AVAILABILITY_CHECK_MS
case SPECIAL_COMMANDS.PAIR_ACTIVE_VAULT:
return REQUEST_TIMEOUT.PAIRING_MS
default:
return REQUEST_TIMEOUT.DEFAULT_MS
}
}
class NativeMessagingHandler {
constructor() {
this.port = null
this.requestId = 0
this.pendingRequests = new Map()
this.connected = false
}
connect() {
if (this.connected) {
log(NATIVE_MESSAGING_ERRORS.ALREADY_CONNECTED)
return Promise.resolve()
}
return new Promise((resolve, reject) => {
try {
log('Connecting to native host:', NATIVE_MESSAGING_CONFIG.HOST_NAME)
this.port = runtime.connectNative(NATIVE_MESSAGING_CONFIG.HOST_NAME)
this.port.onMessage.addListener(this._handleMessage.bind(this))
this.port.onDisconnect.addListener(this._handleDisconnect.bind(this))
this.connected = true
log('Connected to native host')
resolve()
} catch (error) {
logError(NATIVE_MESSAGING_ERRORS.FAILED_TO_CONNECT, error)
reject(error)
}
})
}
disconnect() {
if (this.port) {
this.port.disconnect()
this.port = null
}
this.connected = false
this._clearPendingRequests()
}
/**
* Send a request to the native host
* @param {string} command - The command to send
* @param {Object} params - The parameters to send
* @param {number} timeout - The timeout in milliseconds
* @returns {Promise<any>} The result of the request
*/
sendRequest(command, params = {}, timeout = REQUEST_TIMEOUT.DEFAULT_MS) {
if (!this.connected) {
return this.connect().then(() =>
this.sendRequest(command, params, timeout)
)
}
return new Promise((resolve, reject) => {
const id = ++this.requestId
const request = { id, command, params }
const timeoutId = setTimeout(() => {
this._handleRequestTimeout(id, command)
}, timeout)
this.pendingRequests.set(id, { resolve, reject, timeoutId })
try {
const wrappedRequest = wrapMessage(request)
this.port.postMessage(wrappedRequest)
log('Sent wrapped request:', wrappedRequest)
} catch (error) {
this._cleanupRequest(id)
reject(error)
}
})
}
_handleRequestTimeout(id, command) {
if (this.pendingRequests.has(id)) {
const { reject } = this.pendingRequests.get(id)
this.pendingRequests.delete(id)
reject(createTimeoutError(command))
}
}
_cleanupRequest(id) {
const request = this.pendingRequests.get(id)
if (request) {
clearTimeout(request.timeoutId)
this.pendingRequests.delete(id)
}
}
_clearPendingRequests() {
this.pendingRequests.clear()
}
_handleMessage(message) {
const actualMessage = this._processMessage(message)
if (!actualMessage) return
if (actualMessage.id && this.pendingRequests.has(actualMessage.id)) {
this._handleResponse(actualMessage)
} else if (actualMessage.event) {
this._handleEvent(actualMessage)
}
}
_processMessage(message) {
if (isWrappedMessage(message)) {
const unwrapped = unwrapMessage(message)
if (!unwrapped) {
logError(NATIVE_MESSAGING_ERRORS.FAILED_TO_UNWRAP)
return null
}
log('Unwrapped message:', unwrapped)
return unwrapped
}
log('Received message:', message)
return message
}
_handleResponse(message) {
const { resolve, reject, timeoutId } = this.pendingRequests.get(message.id)
this.pendingRequests.delete(message.id)
if (timeoutId) {
clearTimeout(timeoutId)
}
if (message.success === false || message.error) {
reject(createError(message.error))
} else {
resolve(message.result)
}
}
_handleEvent(message) {
runtime
.sendMessage({
type: NATIVE_MESSAGE_TYPES.EVENT,
event: message.event,
data: message.data
})
.catch((error) => {
log('Failed to forward event to extension:', error?.message || error)
})
}
_handleDisconnect() {
const error = runtime.lastError
logError(NATIVE_MESSAGING_ERRORS.DISCONNECTED, error)
this._rejectAllPendingRequests(error)
this._reset()
this._notifyDisconnection(error)
}
_rejectAllPendingRequests(error) {
for (const { reject } of this.pendingRequests.values()) {
reject(createDisconnectionError(error))
}
this.pendingRequests.clear()
}
_reset() {
this.connected = false
this.port = null
}
_notifyDisconnection(error) {
runtime
.sendMessage({
type: NATIVE_MESSAGE_TYPES.DISCONNECTED,
error: error?.message
})
.catch((notifyError) => {
log(
'Failed to notify disconnection:',
notifyError?.message || notifyError
)
})
}
}
const nativeMessaging = new NativeMessagingHandler()
const SECURE_EXEMPT_COMMANDS = new Set([
SPECIAL_COMMANDS.CHECK_AVAILABILITY,
'nmGetAppIdentity',
'nmBeginHandshake',
'nmFinishHandshake',
'nmSecureRequest',
'nmCloseSession'
])
const shouldSecure = (command) => !SECURE_EXEMPT_COMMANDS.has(command)
/**
* Determine the error code based on the error message
* @param {string} errorMessage - The error message to analyze
* @returns {string} The appropriate error code
*/
const getErrorCode = (errorMessage) => {
if (!errorMessage) return ERROR_CODES.UNKNOWN
// Check for security errors
if (errorMessage.includes(SECURITY_ERROR_PATTERNS.SIGNATURE_INVALID)) {
return ERROR_CODES.SIGNATURE_INVALID
}
if (
errorMessage.includes(SECURITY_ERROR_PATTERNS.IDENTITY_KEYS_UNAVAILABLE)
) {
return ERROR_CODES.IDENTITY_KEYS_UNAVAILABLE
}
if (
errorMessage.includes(SECURITY_ERROR_PATTERNS.DESKTOP_NOT_AUTHENTICATED)
) {
return ERROR_CODES.DESKTOP_NOT_AUTHENTICATED
}
if (errorMessage.includes(AUTH_ERROR_PATTERNS.MASTER_PASSWORD_REQUIRED)) {
return ERROR_CODES.AUTHENTICATION_FAILED
}
if (errorMessage.includes(SECURITY_ERROR_PATTERNS.CLIENT_SIGNATURE_INVALID)) {
return ERROR_CODES.SIGNATURE_INVALID
}
// Check for session errors
if (errorMessage.includes(SESSION_ERROR_PATTERNS.NOT_PAIRED)) {
return ERROR_CODES.NOT_PAIRED
}
if (errorMessage.includes(SESSION_ERROR_PATTERNS.NO_SESSION)) {
return ERROR_CODES.NO_SESSION
}
if (errorMessage.includes(SESSION_ERROR_PATTERNS.SESSION_NOT_FOUND)) {
return ERROR_CODES.NO_SESSION
}
if (errorMessage.includes(SESSION_ERROR_PATTERNS.DECRYPT_FAILED)) {
return ERROR_CODES.NO_SESSION
}
if (
errorMessage.includes(SESSION_ERROR_PATTERNS.HANDSHAKE_FAILED) ||
errorMessage.includes(SESSION_ERROR_PATTERNS.HANDSHAKE_FINISH_FAILED)
) {
return ERROR_CODES.HANDSHAKE_FAILED
}
if (errorMessage.includes(SESSION_ERROR_PATTERNS.SECURE_REQUEST_FAILED)) {
return ERROR_CODES.NO_SESSION
}
// Check for disconnection errors
if (
errorMessage.includes(
DISCONNECTION_ERROR_MESSAGES.NATIVE_HOST_DISCONNECTED
) ||
errorMessage.includes(DISCONNECTION_ERROR_MESSAGES.CONNECTION_FAILED) ||
errorMessage.includes(
DISCONNECTION_ERROR_MESSAGES.DESKTOP_APP_NOT_AVAILABLE
) ||
errorMessage.includes(DESKTOP_APP_STATUS.NOT_RUNNING) ||
errorMessage.includes(DESKTOP_APP_STATUS.INTEGRATION_DISABLED)
) {
return ERROR_CODES.DESKTOP_APP_UNAVAILABLE
}
if (errorMessage.includes(DISCONNECTION_ERROR_MESSAGES.REQUEST_TIMEOUT)) {
return ERROR_CODES.REQUEST_TIMEOUT
}
return ERROR_CODES.UNKNOWN
}
const handleRequest = async (msg, sendResponse) => {
const { command, params: msgParams } = msg
const timeout = getTimeoutForCommand(command)
const params = { ...msgParams, timeout }
try {
let result
// Only secure if paired and command is not exempt
if (shouldSecure(command)) {
await secureChannel.ensureSession()
result = await secureChannel.secureRequest({
method: command,
params,
timeout
})
} else {
result = await nativeMessaging.sendRequest(command, params, timeout)
}
sendResponse({ success: true, result })
} catch (error) {
// Session clearing is handled by secureChannel - just propagate error
sendResponse({
success: false,
error: error.message,
code: getErrorCode(error.message)
})
}
}
const handleConnect = async (msg, sendResponse) => {
try {
await nativeMessaging.connect()
sendResponse({ success: true })
} catch (error) {
const errorCode = getErrorCode(error.message)
sendResponse({
success: false,
error: error.message,
code: errorCode
})
}
}
const handleDisconnect = (msg, sendResponse) => {
nativeMessaging.disconnect()
sendResponse({ success: true })
}
const messageHandlers = {
[NATIVE_MESSAGE_TYPES.REQUEST]: handleRequest,
[NATIVE_MESSAGE_TYPES.CONNECT]: handleConnect,
[NATIVE_MESSAGE_TYPES.DISCONNECT]: handleDisconnect
}
runtime.onMessage.addListener((msg, sender, sendResponse) => {
const handler = messageHandlers[msg.type]
if (handler) {
handler(msg, sendResponse)
return true
}
})
export { nativeMessaging }