-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
background.ts
328 lines (275 loc) 路 10 KB
/
background.ts
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
import browser from 'webextension-polyfill'
import type { Runtime } from 'webextension-polyfill'
import { createEndpointRuntime } from './internal/endpoint-runtime'
import { formatEndpoint, parseEndpoint } from './internal/endpoint'
import { createStreamWirings } from './internal/stream'
import type { EndpointFingerprint } from './internal/endpoint-fingerprint'
import { createFingerprint } from './internal/endpoint-fingerprint'
import { decodeConnectionArgs } from './internal/connection-args'
import type { DeliveryReceipt } from './internal/delivery-logger'
import { createDeliveryLogger } from './internal/delivery-logger'
import type { RequestMessage } from './internal/port-message'
import { PortMessage } from './internal/port-message'
import type { InternalMessage } from './types'
interface PortConnection {
port: Runtime.Port
fingerprint: EndpointFingerprint
}
const pendingResponses = createDeliveryLogger()
const connMap = new Map<string, PortConnection>()
const oncePortConnectedCbs = new Map<string, Set<() => void>>()
const onceSessionEndCbs = new Map<EndpointFingerprint, Set<() => void>>()
const oncePortConnected = (endpointName: string, cb: () => void) => {
oncePortConnectedCbs.set(
endpointName,
(oncePortConnectedCbs.get(endpointName) || new Set()).add(cb),
)
return () => {
const su = oncePortConnectedCbs.get(endpointName)
if (su?.delete(cb) && su?.size === 0)
oncePortConnectedCbs.delete(endpointName)
}
}
const onceSessionEnded = (
sessionFingerprint: EndpointFingerprint,
cb: () => void,
) => {
onceSessionEndCbs.set(
sessionFingerprint,
(onceSessionEndCbs.get(sessionFingerprint) || new Set()).add(cb),
)
}
const notifyEndpoint = (endpoint: string) => ({
withFingerprint: (fingerprint: EndpointFingerprint) => {
const nextChain = <T>(v: T) => ({ and: () => v })
const notifications = {
aboutIncomingMessage: (message: InternalMessage) => {
const recipient = connMap.get(endpoint)
PortMessage.toExtensionContext(recipient.port, {
status: 'incoming',
message,
})
return nextChain(notifications)
},
aboutSuccessfulDelivery: (receipt: DeliveryReceipt) => {
const sender = connMap.get(endpoint)
PortMessage.toExtensionContext(sender.port, {
status: 'delivered',
receipt,
})
return nextChain(notifications)
},
aboutMessageUndeliverability: (
resolvedDestination: string,
message: InternalMessage,
) => {
const sender = connMap.get(endpoint)
if (sender?.fingerprint === fingerprint) {
PortMessage.toExtensionContext(sender.port, {
status: 'undeliverable',
resolvedDestination,
message,
})
}
return nextChain(notifications)
},
whenDeliverableTo: (targetEndpoint: string) => {
const notifyDeliverability = () => {
const origin = connMap.get(endpoint)
if (
origin?.fingerprint === fingerprint
&& connMap.has(targetEndpoint)
) {
PortMessage.toExtensionContext(origin.port, {
status: 'deliverable',
deliverableTo: targetEndpoint,
})
return true
}
}
if (!notifyDeliverability()) {
const unsub = oncePortConnected(targetEndpoint, notifyDeliverability)
onceSessionEnded(fingerprint, unsub)
}
return nextChain(notifications)
},
aboutSessionEnded: (endedSessionFingerprint: EndpointFingerprint) => {
const conn = connMap.get(endpoint)
if (conn?.fingerprint === fingerprint) {
PortMessage.toExtensionContext(conn.port, {
status: 'terminated',
fingerprint: endedSessionFingerprint,
})
}
return nextChain(notifications)
},
}
return notifications
},
})
const sessFingerprint = createFingerprint()
const endpointRuntime = createEndpointRuntime(
'background',
(message) => {
if (
message.origin.context === 'background'
&& ['content-script', 'devtools '].includes(message.destination.context)
&& !message.destination.tabId
) {
throw new TypeError(
'When sending messages from background page, use @tabId syntax to target specific tab',
)
}
const resolvedSender = formatEndpoint({
...message.origin,
...(message.origin.context === 'window' && { context: 'content-script' }),
})
const resolvedDestination = formatEndpoint({
...message.destination,
...(message.destination.context === 'window' && {
context: 'content-script',
}),
tabId: message.destination.tabId || message.origin.tabId,
})
// downstream endpoints are agnostic of these attributes, presence of these attrs will make them think the message is not intended for them
message.destination.tabId = null
message.destination.frameId = null
const dest = () => connMap.get(resolvedDestination)
const sender = () => connMap.get(resolvedSender)
const deliver = () => {
notifyEndpoint(resolvedDestination)
.withFingerprint(dest().fingerprint)
.aboutIncomingMessage(message)
const receipt: DeliveryReceipt = {
message,
to: dest().fingerprint,
from: {
endpointId: resolvedSender,
fingerprint: sender()?.fingerprint,
},
}
if (message.messageType === 'message') pendingResponses.add(receipt)
if (message.messageType === 'reply')
pendingResponses.remove(message.messageID)
if (sender()) {
notifyEndpoint(resolvedSender)
.withFingerprint(sender().fingerprint)
.aboutSuccessfulDelivery(receipt)
}
}
if (dest()?.port) {
deliver()
}
else if (message.messageType === 'message') {
if (message.origin.context === 'background') {
oncePortConnected(resolvedDestination, deliver)
}
else if (sender()) {
notifyEndpoint(resolvedSender)
.withFingerprint(sender().fingerprint)
.aboutMessageUndeliverability(resolvedDestination, message)
.and()
.whenDeliverableTo(resolvedDestination)
}
}
},
(message) => {
const resolvedSender = formatEndpoint({
...message.origin,
...(message.origin.context === 'window' && { context: 'content-script' }),
})
const sender = connMap.get(resolvedSender)
const receipt: DeliveryReceipt = {
message,
to: sessFingerprint,
from: {
endpointId: resolvedSender,
fingerprint: sender.fingerprint,
},
}
notifyEndpoint(resolvedSender)
.withFingerprint(sender.fingerprint)
.aboutSuccessfulDelivery(receipt)
},
)
browser.runtime.onConnect.addListener((incomingPort) => {
const connArgs = decodeConnectionArgs(incomingPort.name)
if (!connArgs) return
// all other contexts except 'content-script' are aware of, and pass their identity as name
connArgs.endpointName ||= formatEndpoint({
context: 'content-script',
tabId: incomingPort.sender.tab.id,
frameId: incomingPort.sender.frameId,
})
// literal tab id in case of content script, however tab id of inspected page in case of devtools context
const { tabId: linkedTabId, frameId: linkedFrameId } = parseEndpoint(
connArgs.endpointName,
)
connMap.set(connArgs.endpointName, {
fingerprint: connArgs.fingerprint,
port: incomingPort,
})
oncePortConnectedCbs.get(connArgs.endpointName)?.forEach(cb => cb())
oncePortConnectedCbs.delete(connArgs.endpointName)
onceSessionEnded(connArgs.fingerprint, () => {
const rogueMsgs = pendingResponses
.entries()
.filter(pendingMessage => pendingMessage.to === connArgs.fingerprint)
pendingResponses.remove(rogueMsgs)
rogueMsgs.forEach((rogueMessage) => {
if (rogueMessage.from.endpointId === 'background') {
endpointRuntime.endTransaction(rogueMessage.message.transactionId)
}
else {
notifyEndpoint(rogueMessage.from.endpointId)
.withFingerprint(rogueMessage.from.fingerprint)
.aboutSessionEnded(connArgs.fingerprint)
}
})
})
incomingPort.onDisconnect.addListener(() => {
// sometimes previous content script's onDisconnect is called *after* the fresh content-script's
// onConnect. So without this fingerprint equality check, we would remove the new port from map
if (
connMap.get(connArgs.endpointName)?.fingerprint === connArgs.fingerprint
)
connMap.delete(connArgs.endpointName)
onceSessionEndCbs.get(connArgs.fingerprint)?.forEach(cb => cb())
onceSessionEndCbs.delete(connArgs.fingerprint)
})
incomingPort.onMessage.addListener((msg: RequestMessage) => {
if (msg.type === 'sync') {
const allActiveSessions = [...connMap.values()].map(
conn => conn.fingerprint,
)
const stillPending = msg.pendingResponses.filter(fp =>
allActiveSessions.includes(fp.to),
)
pendingResponses.add(...stillPending)
msg.pendingResponses
.filter(
deliveryReceipt => !allActiveSessions.includes(deliveryReceipt.to),
)
.forEach(deliveryReceipt =>
notifyEndpoint(connArgs.endpointName)
.withFingerprint(connArgs.fingerprint)
.aboutSessionEnded(deliveryReceipt.to),
)
msg.pendingDeliveries.forEach(intendedDestination =>
notifyEndpoint(connArgs.endpointName)
.withFingerprint(connArgs.fingerprint)
.whenDeliverableTo(intendedDestination),
)
return
}
if (msg.type === 'deliver' && msg.message?.origin?.context) {
// origin tab ID is resolved from the port identifier (also prevent "MITM attacks" of extensions)
msg.message.origin.tabId = linkedTabId
msg.message.origin.frameId = linkedFrameId
endpointRuntime.handleMessage(msg.message)
}
})
})
export const { sendMessage, onMessage } = endpointRuntime
export const { openStream, onOpenStreamChannel }
= createStreamWirings(endpointRuntime)