-
Notifications
You must be signed in to change notification settings - Fork 75
/
messaging.dart
222 lines (197 loc) · 5.27 KB
/
messaging.dart
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
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@JS()
library messaging;
import 'dart:async';
import 'dart:convert';
import 'dart:js_util';
import 'package:js/js.dart';
import 'chrome_api.dart';
import 'data_serializers.dart';
import 'logger.dart';
import 'utils.dart';
// A default response for the sendResponse callback.
//
// Prevents the message port from closing. See:
// https://developer.chrome.com/docs/extensions/mv3/messaging/#simple
final defaultResponse = jsify({'response': 'received'});
enum Script {
background,
copier,
debuggerPanel,
detector,
popup;
factory Script.fromString(String value) {
return Script.values.byName(value);
}
}
enum MessageType {
isAuthenticated,
connectFailure,
appId,
debugInfo,
debugStateChange,
devToolsUrl,
multipleAppsDetected;
factory MessageType.fromString(String value) {
return MessageType.values.byName(value);
}
}
class Message {
final Script to;
final Script from;
final MessageType type;
final String body;
final String? error;
Message({
required this.to,
required this.from,
required this.type,
required this.body,
this.error,
});
factory Message.fromJSON(String json) {
final decoded = jsonDecode(json) as Map<String, dynamic>;
return Message(
to: Script.fromString(decoded['to'] as String),
from: Script.fromString(decoded['from'] as String),
type: MessageType.fromString(decoded['type'] as String),
body: decoded['body'] as String,
error: decoded['error'] as String?,
);
}
String toJSON() {
return jsonEncode({
'to': to.name,
'from': from.name,
'type': type.name,
'body': body,
if (error != null) 'error': error,
});
}
}
void interceptMessage<T>({
required String? message,
required MessageType expectedType,
required Script expectedSender,
required Script expectedRecipient,
required MessageSender sender,
required void Function(T message) messageHandler,
}) {
if (message == null) return;
if (!_isLegitimateSender(sender)) return;
try {
final decodedMessage = Message.fromJSON(message);
if (decodedMessage.type != expectedType ||
decodedMessage.to != expectedRecipient ||
decodedMessage.from != expectedSender) {
return;
}
if (T == String) {
messageHandler(decodedMessage.body as T);
} else {
messageHandler(
serializers.deserialize(jsonDecode(decodedMessage.body)) as T,
);
}
} catch (error) {
debugError(
'Error intercepting $expectedType from $expectedSender to $expectedRecipient: $error',
);
}
}
/// Send a message using the chrome.runtime.sendMessage API.
Future<bool> sendRuntimeMessage({
required MessageType type,
required String body,
required Script sender,
required Script recipient,
}) =>
_sendMessage(
type: type,
body: body,
sender: sender,
recipient: recipient,
);
/// Send a message using the chrome.tabs.sendMessage API.
Future<bool> sendTabsMessage({
required int tabId,
required MessageType type,
required String body,
required Script sender,
required Script recipient,
}) =>
_sendMessage(
tabId: tabId,
type: type,
body: body,
sender: sender,
recipient: recipient,
);
Future<bool> _sendMessage({
required MessageType type,
required String body,
required Script sender,
required Script recipient,
int? tabId,
}) {
final message = Message(
to: recipient,
from: sender,
type: type,
body: body,
).toJSON();
final completer = Completer<bool>();
void responseHandler([dynamic _]) {
final error = chrome.runtime.lastError;
if (error != null) {
debugError(
'Error sending $type to $recipient from $sender: ${error.message}',
);
}
completer.complete(error != null);
}
if (tabId != null) {
chrome.tabs.sendMessage(
tabId,
message,
// options
null,
allowInterop(responseHandler),
);
} else {
chrome.runtime.sendMessage(
// id
null,
message,
// options
null,
allowInterop(responseHandler),
);
}
return completer.future;
}
// Verify the message sender is our extension.
bool _isLegitimateSender(MessageSender sender) {
// Check that the sender ID matches our extension ID:
if (sender.id != chrome.runtime.id) return false;
final senderUri = Uri.parse(sender.origin ?? '');
final senderHost = senderUri.host;
final isDartAppHost = senderHost == 'localhost' ||
senderHost == '127.0.0.1' ||
_isGoogleHost(senderHost);
final isExtensionOrigin =
senderHost == chrome.runtime.id && senderUri.scheme == 'chrome-extension';
if (isDartAppHost || isExtensionOrigin) return true;
// If the sender's host is unexpected, display an error.
displayNotification(
'Unexpected sender ${sender.origin}. Please file a bug at go/dde-bug or https://github.com/dart-lang/webdev',
isError: true,
);
return false;
}
bool _isGoogleHost(String host) {
const googleSuffices = ['.googlers.com', '.google.com', '.googleprod.com'];
return googleSuffices.any((suffix) => host.endsWith(suffix));
}