mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 01:49:19 +08:00
fix: 浏览器扩展 Open API 改经 Background 代发,修复 HTTPS 页面混合内容拦截
This commit is contained in:
@@ -72,9 +72,11 @@ Popup 右上角「配置」:
|
|||||||
|
|
||||||
| 项 | 说明 |
|
| 项 | 说明 |
|
||||||
|----|------|
|
|----|------|
|
||||||
| Base URL | 例 `http://localhost:8080/api`(不要末尾 `/`) |
|
| Base URL | 例 `http://localhost:8080/api`(**直连后端**,不要用前端 dev 的 `5666`;不要末尾 `/`) |
|
||||||
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
|
| API Key | 后台创建的 Open API Key(`sk_...`),**不要**填登录 JWT |
|
||||||
|
|
||||||
|
Open API 请求由 **Background Service Worker 代发**(Content Script 在 HTTPS 拼多多页内不能直连 `http://localhost`,会被混合内容/CORS 拦截,Network 里常无 HTTP 状态码)。
|
||||||
|
|
||||||
Key 建议具备:
|
Key 建议具备:
|
||||||
|
|
||||||
- `open:extension:feature:read`(功能清单/脚本)
|
- `open:extension:feature:read`(功能清单/脚本)
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export default defineManifest({
|
|||||||
host_permissions: ['http://*/*', 'https://*/*'],
|
host_permissions: ['http://*/*', 'https://*/*'],
|
||||||
icons: {
|
icons: {
|
||||||
'16': 'public/icons/icon-16.png',
|
'16': 'public/icons/icon-16.png',
|
||||||
'48': 'public/icons/icon-48.png',
|
'64': 'public/icons/icon-64.png',
|
||||||
'128': 'public/icons/icon-128.png',
|
'128': 'public/icons/icon-128.png',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 602 B After Width: | Height: | Size: 8.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 119 B After Width: | Height: | Size: 433 B |
Binary file not shown.
|
Before Width: | Height: | Size: 242 B |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 KiB |
@@ -1,12 +1,8 @@
|
|||||||
import { ExtensionError } from '@/shared/errors';
|
import { ExtensionError } from '@/shared/errors';
|
||||||
import { getSettings } from '@/storage/settings';
|
|
||||||
|
|
||||||
export interface ApiResponseBody<T> {
|
import { executeOpenApiFetch } from './openApiFetch';
|
||||||
code: number;
|
|
||||||
message: string;
|
|
||||||
data: T;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
export type { ApiResponseBody } from './openApiFetch';
|
||||||
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
|
export type OpenApiRequestFn = <T>(path: string, init?: RequestInit) => Promise<T>;
|
||||||
|
|
||||||
let openApiOverride: OpenApiRequestFn | null = null;
|
let openApiOverride: OpenApiRequestFn | null = null;
|
||||||
@@ -16,6 +12,66 @@ export function setOpenApiRequestOverride(fn: OpenApiRequestFn | null): void {
|
|||||||
openApiOverride = fn;
|
openApiOverride = fn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type OpenApiBgPayload = {
|
||||||
|
path: string;
|
||||||
|
method?: string;
|
||||||
|
body?: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OpenApiBgResponse =
|
||||||
|
| { ok: true; data: unknown }
|
||||||
|
| { ok: false; code: string; message: string };
|
||||||
|
|
||||||
|
function canUseBackgroundProxy(): boolean {
|
||||||
|
return typeof chrome !== 'undefined' && Boolean(chrome.runtime?.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestViaBackground<T>(
|
||||||
|
path: string,
|
||||||
|
init: RequestInit = {},
|
||||||
|
): Promise<T> {
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
if (init.headers) {
|
||||||
|
new Headers(init.headers).forEach((value, key) => {
|
||||||
|
headers[key] = value;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: OpenApiBgPayload = {
|
||||||
|
path,
|
||||||
|
method: init.method,
|
||||||
|
body: typeof init.body === 'string' ? init.body : undefined,
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
let response: OpenApiBgResponse | undefined;
|
||||||
|
try {
|
||||||
|
response = (await chrome.runtime.sendMessage({
|
||||||
|
type: 'OPEN_API_REQUEST',
|
||||||
|
payload,
|
||||||
|
})) as OpenApiBgResponse | undefined;
|
||||||
|
} catch {
|
||||||
|
throw new ExtensionError('NETWORK_ERROR', '无法连接扩展后台,请重载扩展后重试');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response) {
|
||||||
|
throw new ExtensionError('NETWORK_ERROR', '扩展后台无响应');
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ExtensionError(
|
||||||
|
(response.code as ExtensionError['code']) || 'API_REQUEST_FAILED',
|
||||||
|
response.message || '请求失败',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return response.data as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open API 统一入口。
|
||||||
|
* Content Script 在 HTTPS 第三方页内不能直连 HTTP 本地 API(混合内容/CORS),
|
||||||
|
* 默认经 Background 代发。
|
||||||
|
*/
|
||||||
export async function openApiRequest<T>(
|
export async function openApiRequest<T>(
|
||||||
path: string,
|
path: string,
|
||||||
init: RequestInit = {},
|
init: RequestInit = {},
|
||||||
@@ -23,55 +79,8 @@ export async function openApiRequest<T>(
|
|||||||
if (openApiOverride) {
|
if (openApiOverride) {
|
||||||
return openApiOverride<T>(path, init);
|
return openApiOverride<T>(path, init);
|
||||||
}
|
}
|
||||||
|
if (canUseBackgroundProxy()) {
|
||||||
const settings = await getSettings();
|
return requestViaBackground<T>(path, init);
|
||||||
if (!settings.apiBaseUrl) {
|
|
||||||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
|
|
||||||
}
|
}
|
||||||
if (!settings.apiKey) {
|
return executeOpenApiFetch<T>(path, init);
|
||||||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
||||||
const headers = new Headers(init.headers);
|
|
||||||
headers.set('Content-Type', 'application/json');
|
|
||||||
headers.set('X-Api-Key', settings.apiKey);
|
|
||||||
|
|
||||||
let response: Response;
|
|
||||||
try {
|
|
||||||
response = await fetch(url, {
|
|
||||||
...init,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.status === 401) {
|
|
||||||
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
|
|
||||||
}
|
|
||||||
|
|
||||||
let body: ApiResponseBody<T>;
|
|
||||||
try {
|
|
||||||
body = (await response.json()) as ApiResponseBody<T>;
|
|
||||||
} catch {
|
|
||||||
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new ExtensionError(
|
|
||||||
'API_REQUEST_FAILED',
|
|
||||||
body.message || `请求失败(HTTP ${response.status})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 后端业务码:0 / 200 视为成功(兼容)
|
|
||||||
if (body.code !== 0 && body.code !== 200) {
|
|
||||||
throw new ExtensionError(
|
|
||||||
'API_BUSINESS_ERROR',
|
|
||||||
body.message || `业务错误(code=${body.code})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return body.data;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { ExtensionError } from '@/shared/errors';
|
||||||
|
import { getSettings } from '@/storage/settings';
|
||||||
|
|
||||||
|
export interface ApiResponseBody<T> {
|
||||||
|
code: number;
|
||||||
|
message: string;
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在扩展上下文(Background / Popup)内直连 Open API */
|
||||||
|
export async function executeOpenApiFetch<T>(
|
||||||
|
path: string,
|
||||||
|
init: RequestInit = {},
|
||||||
|
): Promise<T> {
|
||||||
|
const settings = await getSettings();
|
||||||
|
if (!settings.apiBaseUrl) {
|
||||||
|
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
|
||||||
|
}
|
||||||
|
if (!settings.apiKey) {
|
||||||
|
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
||||||
|
const headers = new Headers(init.headers);
|
||||||
|
headers.set('Content-Type', 'application/json');
|
||||||
|
headers.set('X-Api-Key', settings.apiKey);
|
||||||
|
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(url, {
|
||||||
|
...init,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: ApiResponseBody<T>;
|
||||||
|
try {
|
||||||
|
body = (await response.json()) as ApiResponseBody<T>;
|
||||||
|
} catch {
|
||||||
|
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ExtensionError(
|
||||||
|
'API_REQUEST_FAILED',
|
||||||
|
body.message || `请求失败(HTTP ${response.status})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.code !== 0 && body.code !== 200) {
|
||||||
|
throw new ExtensionError(
|
||||||
|
'API_BUSINESS_ERROR',
|
||||||
|
body.message || `业务错误(code=${body.code})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return body.data;
|
||||||
|
}
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
|
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
|
||||||
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
|
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
|
||||||
|
* Open API 亦在此代发,避免 HTTPS 页面直连 HTTP 本地服务被混合内容拦截。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { executeOpenApiFetch } from '@/api/openApiFetch';
|
||||||
|
import { ExtensionError } from '@/shared/errors';
|
||||||
|
|
||||||
type InjectMessage = {
|
type InjectMessage = {
|
||||||
type: 'INJECT_MAIN_SCRIPT';
|
type: 'INJECT_MAIN_SCRIPT';
|
||||||
payload: { code: string };
|
payload: { code: string };
|
||||||
@@ -13,7 +17,21 @@ type CallMessage = {
|
|||||||
payload: { featureId: string; action: 'mount' | 'unmount' };
|
payload: { featureId: string; action: 'mount' | 'unmount' };
|
||||||
};
|
};
|
||||||
|
|
||||||
type BgMessage = InjectMessage | CallMessage | { type: 'BACKGROUND_PING' };
|
type OpenApiMessage = {
|
||||||
|
type: 'OPEN_API_REQUEST';
|
||||||
|
payload: {
|
||||||
|
path: string;
|
||||||
|
method?: string;
|
||||||
|
body?: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
type BgMessage =
|
||||||
|
| InjectMessage
|
||||||
|
| CallMessage
|
||||||
|
| OpenApiMessage
|
||||||
|
| { type: 'BACKGROUND_PING' };
|
||||||
|
|
||||||
chrome.runtime.onInstalled.addListener(() => {
|
chrome.runtime.onInstalled.addListener(() => {
|
||||||
console.info('[ecbi-extension] installed');
|
console.info('[ecbi-extension] installed');
|
||||||
@@ -25,6 +43,23 @@ chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (message?.type === 'OPEN_API_REQUEST') {
|
||||||
|
const { path, method, body, headers } = message.payload;
|
||||||
|
void executeOpenApiFetch(path, { method, body, headers })
|
||||||
|
.then((data) => sendResponse({ ok: true, data }))
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
const err =
|
||||||
|
error instanceof ExtensionError
|
||||||
|
? error
|
||||||
|
: new ExtensionError(
|
||||||
|
'UNKNOWN',
|
||||||
|
error instanceof Error ? error.message : 'Open API 请求失败',
|
||||||
|
);
|
||||||
|
sendResponse({ ok: false, code: err.code, message: err.message });
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const tabId = sender.tab?.id;
|
const tabId = sender.tab?.id;
|
||||||
if (tabId == null) {
|
if (tabId == null) {
|
||||||
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
|
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"updatedAt": "2026-08-16T15:10:28.151Z",
|
"updatedAt": "2026-08-26T06:08:57.484Z",
|
||||||
"features": [
|
"features": [
|
||||||
{
|
{
|
||||||
"id": "pdd-ad-fee",
|
"id": "pdd-ad-fee",
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
"https://yingxiao.pinduoduo.com/"
|
"https://yingxiao.pinduoduo.com/"
|
||||||
],
|
],
|
||||||
"entry": "pdd-ad-fee.js",
|
"entry": "pdd-ad-fee.js",
|
||||||
"sha256": "a7f3eb7efc7ccff34e3450b3024bfb591bc953a1d2d1bbd3a3146650e9de36c0",
|
"sha256": "20c8c695a82e9b9c9faa4a8ca9284ce79095cea7fe6260ae647a4437ed4482e9",
|
||||||
"executionWorld": "main"
|
"executionWorld": "main"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user