Skip to content
Merged
Show file tree
Hide file tree
Changes from 19 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
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
307 changes: 307 additions & 0 deletions src/entries/background/utils/nativeMessaging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
import { onMessage, sendMessage } from "@/messages.ts";
import { setupOffscreenDocument } from "./offscreen.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.

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

// Storage and logging (read-only)
"getExtStorage",
"getLogger",
// 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 ──────────────────────────────────────────────
type BridgeState = "no-permission" | "disabled" | "connecting" | "connected" | "retrying" | "error";

let port: chrome.runtime.Port | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let reconnectAttempt = 0;
let permissionGranted = false;
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;
}

function getStatus() {
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.

建议再增加一个 port 的状态,检查是不是为 null

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.

加了

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: 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 (!permissionGranted || !enabled) {
return;
}

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

try {
port = chrome.runtime.connectNative(NATIVE_HOST_NAME);
} 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) return;
port.postMessage({
type: "hello",
instanceId,
browser: __BROWSER__,
extensionId: chrome.runtime.id,
version: __EXT_VERSION__,
capabilities: ["bridge-v1"],
});
state = "connected";
reconnectAttempt = 0;
});

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

const { id, method, params } = msg;

if (!ALLOWED_METHODS.has(method)) {
port!.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);
port?.postMessage({ type: "response", id, result });
} catch (e: any) {
port?.postMessage({
type: "response",
id,
error: { code: "EXTENSION_ERROR", message: e?.message ?? String(e) },
});
}
});

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

port = null;

if (intentionalDisconnect) {
// Intentional disconnect — don't retry
return;
}

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

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

// Recoverable (e.g. host exited) — retry with backoff
lastError = errMsg || "Connection lost";
scheduleReconnect();
});
}

async function init() {
// Refresh permission state
try {
permissionGranted = await chrome.permissions.contains({ permissions: ["nativeMessaging"] });
} catch {
permissionGranted = false;
}

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

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

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

// Permission granted and enabled — connect
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 }) => {
await chrome.storage.local.set({ [ENABLED_KEY]: data });
await init();
// Brief wait for the async hello handshake to complete
if (state === "connecting") {
await new Promise((r) => setTimeout(r, 200));
}
return getStatus();
});

onMessage("nativeBridgeReconnect", async () => {
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();
27 changes: 27 additions & 0 deletions src/entries/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,33 @@ 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(): {
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.

这些返回类型都抽象出来

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.

加了BridgeStatus

permissionGranted: boolean;
enabled: boolean;
state: "no-permission" | "disabled" | "connecting" | "connected" | "retrying" | "error";
connected: boolean;
lastError?: string;
};
nativeBridgeSetEnabled(data: boolean): {
permissionGranted: boolean;
enabled: boolean;
state: "no-permission" | "disabled" | "connecting" | "connected" | "retrying" | "error";
connected: boolean;
lastError?: string;
};
nativeBridgeReconnect(): {
permissionGranted: boolean;
enabled: boolean;
state: "no-permission" | "disabled" | "connecting" | "connected" | "retrying" | "error";
connected: boolean;
lastError?: string;
};
}

// 全局消息处理函数映射
Expand Down
12 changes: 12 additions & 0 deletions src/entries/offscreen/utils/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ export async function getDownloaderConfig(downloaderId: string) {

onMessage("getDownloaderConfig", async ({ data: downloaderId }) => await getDownloaderConfig(downloaderId));

onMessage("getDownloaderList", async () => {
const metadata = (await sendMessage("getExtStorage", "metadata")) as IMetadataPiniaStorageSchema;
const downloaders = metadata?.downloaders ?? {};
return Object.entries(downloaders).map(([id, config]) => ({
id,
name: config.name ?? "",
type: config.type ?? "",
enabled: config.enabled ?? false,
address: config.address ?? "",
}));
});

onMessage("getDownloaderVersion", async ({ data: downloaderId }) => {
let downloaderVersion = "unknown";

Expand Down
2 changes: 1 addition & 1 deletion src/entries/offscreen/utils/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ onMessage("getSiteSearchResult", async ({ data: { siteId, keyword = "", searchEn

if (searchResult.data.length > 0) {
let autoDetectOfficialGroupFromTitlePattern: TPatterns | undefined;
if (configStorage.searchEntity.autoDetectOfficialGroupFromTitle && site.metadata.officialGroupPattern?.length) {
if (configStorage?.searchEntity?.autoDetectOfficialGroupFromTitle && site.metadata.officialGroupPattern?.length) {
autoDetectOfficialGroupFromTitlePattern = site.metadata.officialGroupPattern;
}

Expand Down
Loading
Loading