Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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
148 changes: 148 additions & 0 deletions src/entries/background/utils/nativeMessaging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { 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 RECONNECT_BASE_MS = 1000;
const RECONNECT_MAX_MS = 30000;

/** 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.",
"Native messaging host has exited.",
];

/** 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
"getSiteUserConfig",
"getSiteFavicon",
"clearSiteFaviconCache",
// Search
"getSiteSearchResult",
"getMediaServerSearchResult",
// Download and downloader
"getDownloaderConfig",
"getDownloaderVersion",
"getDownloaderStatus",
"getTorrentDownloadLink",
"getTorrentInfoForVerification",
"downloadTorrent",
"getDownloadHistory",
"getDownloadHistoryById",
"deleteDownloadHistoryById",
"clearDownloadHistory",
// User info
"getSiteUserInfoResult",
"cancelUserInfoQueue",
"getSiteUserInfo",
"removeSiteUserInfo",
// Keep-upload
"getKeepUploadTasks",
"getKeepUploadTaskById",
"createKeepUploadTask",
"updateKeepUploadTask",
"deleteKeepUploadTask",
"clearKeepUploadTasks",
]);

let reconnectAttempt = 0;

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

Check failure on line 58 in src/entries/background/utils/nativeMessaging.ts

View workflow job for this annotation

GitHub Actions / build

Type '{}' is not assignable to type 'string'.
}
const id = crypto.randomUUID();
await chrome.storage.local.set({ [INSTANCE_ID_KEY]: id });
return id;
}

function connect() {
let port: chrome.runtime.Port;
try {
port = chrome.runtime.connectNative(NATIVE_HOST_NAME);
} catch {
// Native host not installed — silently skip
console.debug("[PTD] Native messaging host not available, CLI bridge disabled.");
return;
}

let disconnected = false;
reconnectAttempt = 0;

// Send hello handshake
getOrCreateInstanceId().then((instanceId) => {
if (disconnected) return;
const hello = {
type: "hello",
instanceId,
browser: __BROWSER__,
extensionId: chrome.runtime.id,
version: __EXT_VERSION__,
capabilities: ["bridge-v1"],
};
port.postMessage(hello);
});

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(() => {
disconnected = true;
const err = chrome.runtime.lastError;
if (err) {
console.debug("[PTD] Native messaging disconnected:", err.message);
}

const errMsg = err?.message ?? "";

// Don't retry if the host is not installed or access is denied —
// retrying just floods the console with errors. The user needs to
// install the native host and restart the browser.
if (FATAL_ERRORS.some((e) => errMsg.includes(e))) {
console.debug(
"[PTD] Native host not available, CLI bridge disabled. Install the host and restart the browser to enable.",
);
return;
}

// Reconnect with bounded exponential backoff for transient errors
// (e.g. host process crashed, browser restarted the service worker)
reconnectAttempt++;
const delay = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_MAX_MS);
setTimeout(connect, delay);
});
}

connect();
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
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const permissions = [
"cookies",
"downloads",
"declarativeNetRequest",
"nativeMessaging",
"storage",
"unlimitedStorage",
"notifications",
Expand Down
Loading