Document who can call the loopback API and let the user pick the listen port.

This commit is contained in:
alexveley
2026-09-22 08:19:12 -04:00
parent cfda629418
commit 33944dbd07
10 changed files with 184 additions and 18 deletions
+64 -1
View File
@@ -2,6 +2,7 @@
const HOST_NAME = "com.easygoingaming.firefox_agent_bridge";
const RECONNECT_MS = 2000;
const DEFAULT_PORT = 17634;
const ALLOWED = {
"meta.ping": async () => ({ ok: true, extension: "bookmarks-api" }),
@@ -22,6 +23,47 @@ const ALLOWED = {
let port = null;
let reconnectTimer = null;
let hostUp = false;
let listenPort = DEFAULT_PORT;
let bindError = "";
let configWaiter = null;
function normalizePort(value) {
const n = Number(value);
if (!Number.isInteger(n) || n < 1024 || n > 65535) {
throw new Error("Port must be an integer from 1024 to 65535");
}
return n;
}
async function loadListenPort() {
const data = await browser.storage.local.get("listenPort");
try {
return normalizePort(data.listenPort == null ? DEFAULT_PORT : data.listenPort);
} catch (err) {
return DEFAULT_PORT;
}
}
async function pushConfig() {
if (!port) {
return;
}
listenPort = await loadListenPort();
await new Promise((resolve) => {
configWaiter = resolve;
port.postMessage({ type: "config", port: listenPort });
setTimeout(resolve, 2500);
});
}
function statusInfo() {
return {
hostUp,
port: listenPort,
listenPort,
bindError,
};
}
function asArray(value) {
if (value === undefined || value === null) {
@@ -43,6 +85,16 @@ function attach(nextPort) {
port = nextPort;
hostUp = true;
port.onMessage.addListener(async (message) => {
if (message && message.type === "config-result") {
listenPort = message.port || listenPort;
bindError = message.ok ? "" : (message.error || "could not bind port");
if (configWaiter) {
const done = configWaiter;
configWaiter = null;
done();
}
return;
}
if (message && message.type === "auth") {
try {
const client = await findClientByTokenHash(message.token_hash);
@@ -80,8 +132,10 @@ function attach(nextPort) {
port.onDisconnect.addListener(() => {
port = null;
hostUp = false;
bindError = "";
scheduleReconnect();
});
pushConfig();
}
function scheduleReconnect() {
@@ -106,7 +160,16 @@ function connect() {
browser.runtime.onMessage.addListener((message) => {
if (message && message.type === "status") {
return Promise.resolve({ hostUp, port: 17634 });
return Promise.resolve(statusInfo());
}
if (message && message.type === "set-port") {
return (async () => {
const n = normalizePort(message.port);
await browser.storage.local.set({ listenPort: n });
listenPort = n;
await pushConfig();
return statusInfo();
})();
}
return undefined;
});