Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4bf30c0
feat: add native messaging bridge for CLI communication
LeiShi1313 Mar 30, 2026
cf2b110
fix(native-messaging): narrow stored instance id
LeiShi1313 Mar 30, 2026
914f29d
feat: move nativeMessaging to optional_permissions, bump to 0.0.6
LeiShi1313 Mar 30, 2026
09fdfae
feat: add nativeBridge message types to ProtocolMap
LeiShi1313 Mar 30, 2026
57f6706
feat(native-messaging): rewrite as permission-aware bridge manager
LeiShi1313 Mar 30, 2026
3b2b714
feat: add native-bridge tab route, hide save button for non-config tabs
LeiShi1313 Mar 30, 2026
49a0270
feat: add i18n keys for native bridge settings tab
LeiShi1313 Mar 30, 2026
62382ab
feat: add NativeBridgeWindow settings tab UI
LeiShi1313 Mar 30, 2026
33f9568
fix(native-messaging): remove premature connected state in connect()
LeiShi1313 Mar 30, 2026
145b2a3
fix(native-messaging): add retry budget and poll for test connection …
LeiShi1313 Mar 30, 2026
1fcb807
fix(native-messaging): mark connected after hello handshake send
LeiShi1313 Mar 30, 2026
8b3aabe
feat(native-bridge): show ptd install command when bridge not connected
LeiShi1313 Mar 30, 2026
9bdef03
fix(native-bridge): use correct browser flag in setup command
LeiShi1313 Mar 30, 2026
0a0061f
fix(native-bridge): wait for hello handshake before returning enable …
LeiShi1313 Mar 30, 2026
0b94183
fix(options): redirect /settings to /set-base by default
LeiShi1313 Mar 30, 2026
1409306
fix(options): move native bridge tab before backup & restore
LeiShi1313 Mar 30, 2026
ca230b7
feat(native-bridge): link to ptd-cli repo in info section
LeiShi1313 Mar 30, 2026
80304d5
feat: add getSiteList and getDownloaderList message handlers
LeiShi1313 Mar 30, 2026
2161d96
fix(native-bridge): update ptd-cli link to pt-plugins org repo
LeiShi1313 Mar 31, 2026
7b0749d
fix(native-bridge): address PR review feedback
LeiShi1313 Mar 31, 2026
797c73d
fix(native-bridge): add address back to downloader list, add privacy …
LeiShi1313 Apr 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "pt-depiler",
"private": true,
"version": "0.0.5",
"version": "0.0.6",
"type": "module",
"homepage": "https://github.com/pt-plugins/PT-depiler",
"packageManager": "pnpm@10.21.0",
Expand Down
12 changes: 9 additions & 3 deletions privacy-statement.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@
- 使用 `https` 的方式配置服务器地址;
- 启用备份数据加密(采用 [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard))功能后再进行备份操作;

## 四、与第三人共用个人信息之政策
## 四、原生通信桥(Native Messaging)
- 当您在设置页面中授予 `nativeMessaging` 权限并启用原生通信桥功能后,助手将通过 Chrome Native Messaging 机制与本地安装的 CLI 工具(ptd-cli)进行通信;
- 通过此通道可访问的信息包括:站点配置、搜索结果、下载历史、用户信息、下载器状态等;
- 所有通信均在本地进行(浏览器与本机进程之间),不会将数据发送至任何远程服务器;
- 此功能为可选功能,需要用户主动授权并启用,您可以随时在设置页面中撤销权限或禁用该功能;

## 五、与第三人共用个人信息之政策
- 助手不会收集任何相关的个人信息,所以助手绝不会提供、交换、出租或出售任何您的个人信息给其他个人、团体、私人企业或公务机关;

## 、Cookie之使用
## 、Cookie之使用
- 当您进行搜索操作时,助手会访问您已配置的站点,Cookie 由浏览器提供,助手无权访问也不会对内容进行探测和修改,一切内容由浏览器和站点进行相互验证;
- 当您授权助手访问 Cookie 信息时,这些信息仅用于备份和恢复操作,助手不会在除此之外的任何其他操作中使用它们;

## 、隐私权保护政策之修正
## 、隐私权保护政策之修正
- 助手隐私权保护政策将按用户需求变更而随时进行修正,修正后的条款将在本页面显示。
1 change: 1 addition & 0 deletions src/entries/background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import "./utils/contextMenus.ts";
import "./utils/omnibox.ts";
import "./utils/alarms.ts";
import "./utils/webRequest.ts";
import "./utils/nativeMessaging.ts";

// 监听 点击图标 事件
chrome.action.onClicked.addListener(async () => {
Expand Down
335 changes: 335 additions & 0 deletions src/entries/background/utils/nativeMessaging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,335 @@
import { onMessage, sendMessage } from "@/messages.ts";
import { setupOffscreenDocument } from "./offscreen.ts";
import type { BridgeState, BridgeStatus } from "@/shared/types.ts";

const NATIVE_HOST_NAME = "com.ptd.native";
const INSTANCE_ID_KEY = "ptd_native_instance_id";
const ENABLED_KEY = "ptd_native_bridge_enabled";
const RECONNECT_BASE_MS = 1000;
const RECONNECT_MAX_MS = 30000;
const MAX_RECONNECT_ATTEMPTS = 10;

/** Errors that indicate the native host is not installed — no point retrying. */
const FATAL_ERRORS = [
"Specified native messaging host not found.",
"Access to the specified native messaging host is forbidden.",
];

/** Methods the bridge will proxy to sendMessage(). Everything else is rejected. */
const ALLOWED_METHODS = new Set([
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CLI 能够使用的 sendMessage methods 有必要进一步细分吗?比如按 site, search, download, userInfo, keepUpload 这种大类?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这现阶段应该问题不大,还没有那么多方法到让人困惑的地步

// Site config
"getSiteList",
"getSiteUserConfig",
"getSiteFavicon",
"clearSiteFaviconCache",
// Search
"getSiteSearchResult",
"getMediaServerSearchResult",
// Download and downloader
"getDownloaderList",
"getDownloaderConfig",
"getDownloaderVersion",
"getDownloaderStatus",
"getTorrentDownloadLink",
"getTorrentInfoForVerification",
"downloadTorrent",
"getDownloadHistory",
"getDownloadHistoryById",
"deleteDownloadHistoryById",
"clearDownloadHistory",
// User info
"getSiteUserInfoResult",
"cancelUserInfoQueue",
"getSiteUserInfo",
"removeSiteUserInfo",
// Keep-upload
"getKeepUploadTasks",
"getKeepUploadTaskById",
"createKeepUploadTask",
"updateKeepUploadTask",
"deleteKeepUploadTask",
"clearKeepUploadTasks",
]);

// ── Module-scoped state ──────────────────────────────────────────────

let port: chrome.runtime.Port | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let reconnectAttempt = 0;
let enabled = true;
let state: BridgeState = "no-permission";
let lastError: string | undefined;
let intentionalDisconnect = false;

// ── Helpers ──────────────────────────────────────────────────────────

async function getOrCreateInstanceId(): Promise<string> {
const stored = await chrome.storage.local.get(INSTANCE_ID_KEY);
const storedInstanceId = stored[INSTANCE_ID_KEY];

if (typeof storedInstanceId === "string" && storedInstanceId.length > 0) {
return storedInstanceId;
}
const id = crypto.randomUUID();
await chrome.storage.local.set({ [INSTANCE_ID_KEY]: id });
return id;
}

async function checkPermission(): Promise<boolean> {
try {
return await chrome.permissions.contains({ permissions: ["nativeMessaging"] });
} catch {
return false;
}
}

async function getStatus(): Promise<BridgeStatus> {
const permissionGranted = await checkPermission();
return {
permissionGranted,
Copy link
Copy Markdown
Collaborator

@Rhilip Rhilip Mar 31, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

此处的 permissionGranted 建议动态获取,因为下面的 onAdded 以及 onRemoved 在重复授权的情况下不会触发,在极端条件下会导致已授权的在设置页面仍然显示未授权(需要reload插件解决)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

enabled,
state,
connected: port !== null && state === "connected",
lastError,
};
}

function clearReconnectTimer() {
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}

// ── Lifecycle ────────────────────────────────────────────────────────

function disconnect(intentional: boolean) {
intentionalDisconnect = intentional;
clearReconnectTimer();
reconnectAttempt = 0;

if (port) {
try {
port.disconnect();
} catch {
// Already disconnected — ignore
}
port = null;
}
}

function scheduleReconnect() {
clearReconnectTimer();
reconnectAttempt++;

if (reconnectAttempt > MAX_RECONNECT_ATTEMPTS) {
state = "error";
lastError = `Gave up after ${MAX_RECONNECT_ATTEMPTS} reconnect attempts`;
console.debug("[PTD] Native bridge exceeded max reconnect attempts, giving up.");
return;
}

const delay = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_MAX_MS);
state = "retrying";
console.debug(
`[PTD] Native bridge reconnecting in ${delay}ms (attempt ${reconnectAttempt}/${MAX_RECONNECT_ATTEMPTS})...`,
);
reconnectTimer = setTimeout(connect, delay);
}

function connect() {
if (!enabled) {
return;
}

clearReconnectTimer();
state = "connecting";
lastError = undefined;
intentionalDisconnect = false;

let currentPort: chrome.runtime.Port;
try {
currentPort = chrome.runtime.connectNative(NATIVE_HOST_NAME);
port = currentPort;
} catch (e: any) {
state = "error";
lastError = e?.message ?? String(e);
console.debug("[PTD] Native messaging host not available:", lastError);
return;
}

// Send hello handshake — mark connected after successful send.
// The native host does not send an ack, so a successful postMessage
// is our best signal. If the host is absent, onDisconnect fires.
getOrCreateInstanceId()
.then((instanceId) => {
if (port !== currentPort) return;

try {
currentPort.postMessage({
type: "hello",
instanceId,
browser: __BROWSER__,
extensionId: chrome.runtime.id,
version: __EXT_VERSION__,
capabilities: ["bridge-v1"],
});
} catch (e: any) {
state = "error";
lastError = e?.message ?? String(e);
console.debug("[PTD] Failed to send native hello message:", lastError);
return;
}

state = "connected";
reconnectAttempt = 0;
})
.catch((e: any) => {
if (port !== currentPort) return;
state = "error";
lastError = e?.message ?? String(e);
console.debug("[PTD] Failed to get or create native instance id:", lastError);
try {
currentPort.disconnect();
} catch {
// ignore
}
});

currentPort.onMessage.addListener(async (msg: any) => {
if (msg?.type !== "request" || !msg.id || !msg.method) {
return;
}

const { id, method, params } = msg;

if (!ALLOWED_METHODS.has(method)) {
currentPort.postMessage({
type: "response",
id,
error: { code: "METHOD_NOT_ALLOWED", message: `Method '${method}' is not allowed` },
});
return;
}

try {
await setupOffscreenDocument();
const result = await sendMessage(method as any, params);
if (port === currentPort) {
currentPort.postMessage({ type: "response", id, result });
}
} catch (e: any) {
if (port === currentPort) {
currentPort.postMessage({
type: "response",
id,
error: { code: "EXTENSION_ERROR", message: e?.message ?? String(e) },
});
}
}
});

currentPort.onDisconnect.addListener(() => {
const err = chrome.runtime.lastError;
const errMsg = err?.message ?? "";

// Stale port — a new connection has already replaced this one
if (port !== currentPort) return;

port = null;

if (intentionalDisconnect) {
return;
}

if (err) {
console.debug("[PTD] Native messaging disconnected:", errMsg);
}

if (FATAL_ERRORS.some((e) => errMsg.includes(e))) {
state = "error";
lastError = errMsg;
console.debug("[PTD] Native host not available, CLI bridge disabled.");
return;
}

lastError = errMsg || "Connection lost";
scheduleReconnect();
});
}

async function init() {
const permissionGranted = await checkPermission();

// Refresh enabled flag
const stored = await chrome.storage.local.get(ENABLED_KEY);
enabled = stored[ENABLED_KEY] !== false; // default true

if (!permissionGranted) {
disconnect(true);
state = "no-permission";
lastError = undefined;
return;
}

if (!enabled) {
disconnect(true);
state = "disabled";
lastError = undefined;
return;
}

connect();
}

// ── Runtime permission listeners ─────────────────────────────────────

chrome.permissions.onAdded?.addListener((permissions) => {
if (permissions.permissions?.includes("nativeMessaging")) {
init();
}
});

chrome.permissions.onRemoved?.addListener((permissions) => {
if (permissions.permissions?.includes("nativeMessaging")) {
init();
}
});

// ── Message handlers ─────────────────────────────────────────────────

onMessage("nativeBridgeGetStatus", async () => {
return getStatus();
});

onMessage("nativeBridgeSetEnabled", async ({ data }) => {
if (typeof data !== "boolean") {
return getStatus();
}
await chrome.storage.local.set({ [ENABLED_KEY]: data });
await init();
if (state === "connecting") {
await new Promise((r) => setTimeout(r, 200));
}
return getStatus();
});

onMessage("nativeBridgeReconnect", async () => {
const permissionGranted = await checkPermission();
if (!permissionGranted) {
lastError = "Permission not granted — cannot reconnect";
return getStatus();
}
if (!enabled) {
lastError = "Bridge is disabled — cannot reconnect";
return getStatus();
}

disconnect(true);
connect();
return getStatus();
});

// ── Startup ──────────────────────────────────────────────────────────

init();
10 changes: 10 additions & 0 deletions src/entries/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
AugmentedRequired,
IKeepUploadTask,
TKeepUploadTaskKey,
BridgeStatus,
} from "@/shared/types.ts";

import { isDebug } from "~/helper.ts";
Expand Down Expand Up @@ -145,6 +146,15 @@ interface ProtocolMap extends TMessageMap {
updateKeepUploadTask(task: IKeepUploadTask): void;
deleteKeepUploadTask(taskId: TKeepUploadTaskKey): void;
clearKeepUploadTasks(): void;

// 2.8 Lightweight list queries (for CLI discovery)
getSiteList(): Array<{ id: string; name: string; url: string; offline: boolean }>;
getDownloaderList(): Array<{ id: string; name: string; type: string; enabled: boolean; address: string }>;

// 2.9 Native messaging bridge control
nativeBridgeGetStatus(): BridgeStatus;
nativeBridgeSetEnabled(data: boolean): BridgeStatus;
nativeBridgeReconnect(): BridgeStatus;
}

// 全局消息处理函数映射
Expand Down
Loading
Loading