-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
308 lines (269 loc) · 10.2 KB
/
content.js
File metadata and controls
308 lines (269 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
// Content Script (ISOLATED world)
// 作为桥接层,负责在页面脚本和扩展API之间传递消息
(function() {
'use strict';
// 读取配置并注入对应脚本
chrome.storage.local.get([
'webauthn_compat_mode',
'webauthn_allow_polyfill_override'
], (result) => {
const compatMode = result.webauthn_compat_mode || false;
const allowPolyfillOverride = result.webauthn_allow_polyfill_override !== false; // 默认 true
// 根据兼容模式配置选择注入的脚本
const scriptFile = compatMode ? 'inject-compat.js' : 'inject.js';
// 注入脚本到页面的MAIN world
const script = document.createElement('script');
script.src = chrome.runtime.getURL(scriptFile);
// 通过 dataset 传递配置到注入的脚本
script.dataset.allowPolyfillOverride = String(allowPolyfillOverride);
script.onnload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(script);
});
// 检查扩展上下文是否有效
function isExtensionContextValid() {
try {
return !!chrome.runtime?.id;
} catch (e) {
return false;
}
}
// 监听来自页面的消息
window.addEventListener('message', function(event) {
// 只接受来自同源的消息
if (event.source !== window) return;
// 处理配置查询请求
if (event.data && event.data.type === 'WEBAUTHN_GET_CONFIG') {
const { requestId, configKey } = event.data;
if (!isExtensionContextValid()) {
window.postMessage({
type: 'WEBAUTHN_CONFIG_RESPONSE',
requestId: requestId,
enabled: false
}, '*');
return;
}
// 直接读取配置并返回(无需经过 background)
try {
chrome.storage.local.get([configKey], (result) => {
window.postMessage({
type: 'WEBAUTHN_CONFIG_RESPONSE',
requestId: requestId,
enabled: result[configKey] || false
}, '*');
});
} catch (error) {
console.error('[WebAuthn Compat] 读取配置失败:', error);
window.postMessage({
type: 'WEBAUTHN_CONFIG_RESPONSE',
requestId: requestId,
enabled: false
}, '*');
}
return;
}
// 处理兼容模式存储请求
if (event.data && event.data.type === 'WEBAUTHN_STORAGE_REQUEST') {
handleStorageRequest(event.data);
return;
}
if (event.data && (event.data.type === 'WEBAUTHN_CREATE' || event.data.type === 'WEBAUTHN_GET')) {
const { type, requestId, options } = event.data;
// 检查扩展上下文是否有效
if (!isExtensionContextValid()) {
window.postMessage({
type: 'WEBAUTHN_RESPONSE',
requestId: requestId,
success: false,
error: 'The operation either timed out or was not allowed.'
}, '*');
return;
}
// options 已经在 inject.js 中序列化过了,直接使用
// 转发到background script (V3: 不等待响应,通过推送监听器接收结果)
const messageType = type === 'WEBAUTHN_CREATE' ? 'webauthn_create' : 'webauthn_get';
try {
chrome.runtime.sendMessage({
type: messageType,
options: options,
requestId: requestId // 传递requestId供background使用
});
} catch (error) {
// 扩展上下文失效(扩展被重新加载或禁用)
console.error('[WebAuthn Compat] Failed to send message:', error);
window.postMessage({
type: 'WEBAUTHN_RESPONSE',
requestId: requestId,
success: false,
error: 'The operation either timed out or was not allowed.'
}, '*');
}
// V3: 响应将通过 chrome.runtime.onMessage 监听器接收 (见下方推送监听器)
}
});
// V3: 监听来自background的主动推送
chrome.runtime.onMessage.addListener((message, sender) => {
if (message.type === 'webauthn_response') {
// 转发给页面
window.postMessage({
type: 'WEBAUTHN_RESPONSE',
requestId: message.requestId,
success: message.success,
credential: message.credential,
error: message.error
}, '*');
} else if (message.type === 'webauthn_config_response') {
// 转发配置响应给页面
window.postMessage({
type: 'WEBAUTHN_CONFIG_RESPONSE',
requestId: message.requestId,
enabled: message.enabled
}, '*');
}
});
// ==================== 兼容模式存储桥接处理器 ====================
// 辅助函数: ArrayBuffer 转 hex 字符串
function bufferToHex(buffer) {
return Array.from(new Uint8Array(buffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// 辅助函数: hex 字符串转 ArrayBuffer
function hexToBuffer(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return bytes.buffer;
}
// 辅助函数: Array/ArrayBuffer 转 Base64URL
function arrayToBase64url(array) {
const bytes = new Uint8Array(array);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
// 存储请求处理函数
async function handleStorageRequest(data) {
const { requestId, operation, data: opData } = data;
try {
let result;
switch (operation) {
case 'save':
// 保存凭证
const allData = await new Promise(resolve =>
chrome.storage.local.get(['webauthn_credentials'], r =>
resolve(r.webauthn_credentials || {})));
if (!allData[opData.rpId]) {
allData[opData.rpId] = {};
}
// 序列化 ArrayBuffer → hex
const storableCred = {
publicKey: bufferToHex(opData.credential.publicKey),
privateKey: bufferToHex(opData.credential.privateKey),
counter: opData.credential.counter,
algorithm: opData.credential.algorithm,
userHandle: bufferToHex(opData.credential.userHandle),
userId: opData.credential.userId,
userName: opData.credential.userName,
userDisplayName: opData.credential.userDisplayName,
rpId: opData.credential.rpId,
rpName: opData.credential.rpName,
createTime: opData.credential.createTime
};
allData[opData.rpId][opData.credentialId] = storableCred;
await new Promise(resolve =>
chrome.storage.local.set({ webauthn_credentials: allData }, resolve));
result = { success: true };
break;
case 'find':
// 查找凭证(返回 Array 格式)
const credentials = await new Promise(resolve => {
chrome.storage.local.get(['webauthn_credentials'], r => {
const allCreds = r.webauthn_credentials || {};
const rpCreds = allCreds[opData.rpId] || {};
const result = [];
for (const [credId, cred] of Object.entries(rpCreds)) {
// allowCredentials 过滤
if (opData.allowCredentials?.length > 0) {
const allowed = opData.allowCredentials.some(a =>
arrayToBase64url(a.id) === credId);
if (!allowed) continue;
}
result.push({
credentialId: credId,
publicKey: Array.from(new Uint8Array(hexToBuffer(cred.publicKey))),
privateKey: Array.from(new Uint8Array(hexToBuffer(cred.privateKey))),
counter: cred.counter,
algorithm: cred.algorithm || -7,
userHandle: Array.from(new Uint8Array(hexToBuffer(cred.userHandle))),
userId: cred.userId,
userName: cred.userName,
userDisplayName: cred.userDisplayName,
rpId: cred.rpId,
rpName: cred.rpName,
createTime: cred.createTime
});
}
resolve(result);
});
});
result = credentials;
break;
case 'updateCounter':
// 更新计数器
const updateData = await new Promise(resolve =>
chrome.storage.local.get(['webauthn_credentials'], r =>
resolve(r.webauthn_credentials || {})));
if (updateData[opData.rpId]?.[opData.credentialId]) {
updateData[opData.rpId][opData.credentialId].counter = opData.counter;
await new Promise(resolve =>
chrome.storage.local.set({ webauthn_credentials: updateData }, resolve));
}
result = { success: true };
break;
case 'getConfig':
// 读取配置
result = await new Promise(resolve =>
chrome.storage.local.get([opData.key], r => resolve(r[opData.key] || false)));
break;
case 'getByRpId':
// 获取所有凭证(用于 excludeCredentials 检查)
const rpData = await new Promise(resolve =>
chrome.storage.local.get(['webauthn_credentials'], r => {
const allCreds = r.webauthn_credentials || {};
resolve(allCreds[opData.rpId] || {});
}));
result = {};
for (const [credId, cred] of Object.entries(rpData)) {
result[credId] = {
publicKey: Array.from(new Uint8Array(hexToBuffer(cred.publicKey))),
privateKey: Array.from(new Uint8Array(hexToBuffer(cred.privateKey))),
userHandle: Array.from(new Uint8Array(hexToBuffer(cred.userHandle)))
};
}
break;
default:
throw new Error('Unknown operation: ' + operation);
}
// 返回成功
window.postMessage({
type: 'WEBAUTHN_STORAGE_RESPONSE',
requestId,
success: true,
result
}, '*');
} catch (error) {
console.error('[WebAuthn Compat] 存储操作失败:', error);
window.postMessage({
type: 'WEBAUTHN_STORAGE_RESPONSE',
requestId,
success: false,
error: error.message
}, '*');
}
}
})();