Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
stop the SSRF pin from counting a canceled navigation as one still in flight
[._.]/ Adam Eivy905274d21209
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 77e277dafb..96a49a83f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -114,6 +114,7 @@## Stacker News stewardship+- **Check browser identity no longer fails at random with "a top-level navigation was still in flight".** The SSRF pin watches every top-level navigation the page starts and refuses to read the page while one is unaccounted for. But a single-page app cancels its own navigations routinely — a route change during hydration supersedes the one already in flight, and Chrome reports that as an aborted load with no response — and the pin counted an aborted navigation as one that might still be connecting somewhere private. A load Chrome has given up on can never put a document on screen, so it no longer holds the read hostage; a navigation that is genuinely still open is still a refusal, and the refusal now names the URL it was headed to instead of leaving you to guess. The identity check also stops leaving a `stacker.news` tab open in your browser every time you run it — and every handoff ran it first, so a day of stewardship piled up a row of duplicate tabs. Catalog's "ingest from URL" had the same leak and is fixed alongside it: both read the page on the browser connection they opened, so neither has any use for the tab afterwards.- **[issue-3315] The Stacker News vision-model picker now only offers models that can actually see an image.** It listed every installed Ollama model — coder and embedding models included — and picking one was silently accepted, so a model that cannot read an image still produced a confident-looking "vision" verdict that fed the safety policy gating the account's actions. The picker now shows the same vision-capable list the rest of PortOS uses (the server's per-model capability report unioned with the id heuristic, so a brand-new multimodal family still shows up), the text picker is untouched, a model you configured earlier is preserved even if it no longer qualifies, and the form now says whether it is still checking capabilities or has confirmed you have no vision model installed.- **[issue-3317] Check browser identity now works on sites whose service worker serves the page.** The SSRF pin behind every browser handoff verifies the address Chrome actually dialled for the main document, and refuses anything it cannot verify — but a service-worker-mediated document carries no peer address even when the worker passed the fetch straight through to the network, so identity checks against any PWA failed 100% of the time with "Chrome connected to an unverifiable address". The pinned tab now bypasses the site's service worker and its cache so Chrome fetches the document itself and reports a real address to verify, cookies and the signed-in session being unaffected. The fail-closed rule is unchanged: an unexplained missing address is still a refusal, and only a hop Chrome explicitly reported as served with no connection at all is exempt — and only when another hop of the *same* navigation verified a real address and the hop's own URL host is allowed, so a cached document can never borrow an unrelated navigation's verification. Refusals now name the delivery flags that caused them, so the next one is diagnosable from the message.- **[issue-3318] Stacker News reads now go through the signed-in pinned browser, so Sync now works without an API key.** Every read — the identity check, the territory-settings refresh, and the item sync — used to demand a Stacker News API key, and SN does not hand those out from a settings page: you post an "[API Key Request]" thread and wait for the team to grant one. So a normal install would configure an account, click **Sync now**, and get `Stacker News API key is not configured` with nothing to do about it. Reads now default to a browser transport that navigates the same fixed `stacker.news` URLs the handoffs already use and reads the page's own server-rendered data, so an account whose pinned browser is signed in syncs with no key at all — including paging past the first page, which follows the cursor the page hands back. Browser-sourced posts are indistinguishable from API-sourced ones downstream: same bounding, same content hash, same untrusted-content screening, same columns. A read refuses anything that did not land on exactly the page it asked for, since Stacker News redirects a renamed territory to a different one and that page's owner ID would otherwise become the configured territory's ownership evidence; a failed extraction is an error rather than a quiet empty sync; and the identity check the sync runs is the same extractor **Check browser identity** uses, so the two can't disagree. Accounts carry a **Read transport** setting — browser by default, with accounts that already hold a key kept on the API so their schedules don't change under them — and the key is now labelled optional and needed only for reviewed publishing, which still requires it and still refuses without one. **Check API identity** is disabled with an explanation when no key is stored instead of failing with a bare error.diff --git a/server/services/browserService.js b/server/services/browserService.jsindex bbe25467a9..b029b94db4 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -349,7 +349,9 @@ const describeHopDelivery = (hop) => `no remoteIPAddress; fromServiceWorker=${ho* browser. Returns `{ hops: [{ requestId, url, remoteIPAddress, status,* fromServiceWorker, fromDiskCache, fromPrefetchCache,* serviceWorkerResponseSource }], finalUrl, mainRequestIds: string[],- * pendingMainRequestIds: string[] }`. The delivery flags ride along so the gate+ * pendingMainRequestIds: string[], pendingMainRequestUrls: string[] }` (the+ * URLs are positional to the pending ids, so a refusal can name the destination+ * without re-parsing the stream). The delivery flags ride along so the gate* can tell "Chrome dialed somewhere we can't see" apart from "Chrome made no* connection at all" (see `hopMadeNoConnection`), and `requestId` keeps the hops* of ONE top-level navigation distinguishable from another's.@@ -357,7 +359,11 @@ const describeHopDelivery = (hop) => `no remoteIPAddress; fromServiceWorker=${ho* `responseReceived` in the captured window — i.e. a navigation still in flight* whose final connection IP was never observed. The caller must fail closed on a* non-empty pending set: Chrome could complete that navigation (to a private /- * metadata target) right after we stop capturing, leaving it unpinned.+ * metadata target) right after we stop capturing, leaving it unpinned. A+ * navigation Chrome reported as FAILED (`Network.loadingFailed` — most often+ * `net::ERR_ABORTED` when a client-side route change supersedes an in-flight+ * one) is NOT pending: it is dead, it can never commit a document, and there is+ * no connection left to complete after we stop capturing.*/export function pickMainFrameHops(messages, topFrameId = null) {// CDP sets `requestId === loaderId` on the main resource of EVERY frame — the@@ -376,6 +382,10 @@ export function pickMainFrameHops(messages, topFrameId = null) {&& (useFrameId ? p.frameId === topFrameId : p.requestId === p.loaderId);const mainRequestIds = new Set();const respondedIds = new Set();+ const failedIds = new Set();+ // Latest requested URL per main-frame navigation (a redirect overwrites it),+ // so a pending navigation can be NAMED in the refusal without a second parse.+ const mainRequestUrls = new Map();const hops = [];let finalUrl = null;for (const msg of messages) {@@ -385,8 +395,9 @@ export function pickMainFrameHops(messages, topFrameId = null) {if (isMainDocRequest(p)) {mainRequestIds.add(p.requestId);}- if (mainRequestIds.has(p.requestId) && p.redirectResponse) {- hops.push(toHop(p.redirectResponse, p.requestId));+ if (mainRequestIds.has(p.requestId)) {+ if (p.request?.url) mainRequestUrls.set(p.requestId, p.request.url);+ if (p.redirectResponse) hops.push(toHop(p.redirectResponse, p.requestId));}} else if (msg.method === 'Network.responseReceived') {if (mainRequestIds.has(p.requestId) && p.response) {@@ -394,10 +405,22 @@ export function pickMainFrameHops(messages, topFrameId = null) {hops.push(toHop(p.response, p.requestId));finalUrl = p.response.url || finalUrl;}+ } else if (msg.method === 'Network.loadingFailed' && mainRequestIds.has(p.requestId)) {+ // Chrome gave up on this load — no document will ever commit from it. A+ // failure that arrives AFTER the response is only the body being cut+ // short, and that hop is already pinned, so `respondedIds` still wins.+ failedIds.add(p.requestId);}}- const pendingMainRequestIds = [...mainRequestIds].filter((id) => !respondedIds.has(id));- return { hops, finalUrl, mainRequestIds: [...mainRequestIds], pendingMainRequestIds };+ const pendingMainRequestIds = [...mainRequestIds]+ .filter((id) => !respondedIds.has(id) && !failedIds.has(id));+ return {+ hops,+ finalUrl,+ mainRequestIds: [...mainRequestIds],+ pendingMainRequestIds,+ pendingMainRequestUrls: pendingMainRequestIds.map((id) => mainRequestUrls.get(id) || '(url unknown)'),+ };}// Session-scoped CDP commands the pinned tab issues after `Network.enable` and@@ -468,7 +491,7 @@ export function collectWebSocketHosts(messages) {// Pure gate over a captured CDP message stream: returns a refusal reason string,// or null when the navigation is safe to read. Exported for unit testing.export function ssrfPinRefusalReason(messages, verifyRemoteIp, url, topFrameId = null) {- const { hops, pendingMainRequestIds } = pickMainFrameHops(messages, topFrameId);+ const { hops, pendingMainRequestUrls } = pickMainFrameHops(messages, topFrameId);if (!hops.length) return 'no main-frame document response was observed';// The main document must have a verifiable (present) connection IP — an empty// one can't be checked, so fail closed. The ONE exception is a hop Chrome@@ -496,9 +519,13 @@ export function ssrfPinRefusalReason(messages, verifyRemoteIp, url, topFrameId =: describeHopDelivery(hop);return `Chrome connected to an unverifiable address for ${hop.url || url} (${detail})`;}- // A top-level navigation that STARTED but produced no response was never- // pinned — Chrome could be mid-connect to a private/metadata target.- if (pendingMainRequestIds.length) return 'a top-level navigation was still in flight (unpinned)';+ // A top-level navigation that STARTED, produced no response, and was not+ // reported as failed was never pinned — Chrome could be mid-connect to a+ // private/metadata target. Name the URL(s): the bare message is undiagnosable+ // once the capture window is gone.+ if (pendingMainRequestUrls.length) {+ return `a top-level navigation was still in flight (unpinned): ${pendingMainRequestUrls.join(', ')}`;+ }// EVERY connection Chrome made must dial an allowed address — not just the// main document. A rebinding page can load public, then `fetch()` its// now-private-resolving hostname; the browser treats it as same-origin, JSdiff --git a/server/services/browserService.test.js b/server/services/browserService.test.jsindex a0a657d2ed..9a1da46112 100644--- a/server/services/browserService.test.js+++ b/server/services/browserService.test.js@@ -3,6 +3,14 @@ import { mkdir, readFile, rm, utimes, writeFile } from 'fs/promises';import { join } from 'path';import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+// Shape captured from Chrome 150 when a second top-level navigation supersedes+// an in-flight one: no `responseReceived` ever arrives for the canceled id.+// Shared by both SSRF-pin suites below so the CDP shape is written once.+const loadingFailed = (requestId, errorText) => ({+ method: 'Network.loadingFailed',+ params: { requestId, type: 'Document', errorText, canceled: errorText === 'net::ERR_ABORTED' },+});+describe('browserService config persistence', () => {let tempRoot;@@ -173,6 +181,35 @@ describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {expect(hops.map((h) => h.remoteIPAddress)).toEqual(['93.184.216.34']);});+ it('drops a canceled top-level navigation from pending (loadingFailed, no response)', () => {+ const { mainRequestIds, pendingMainRequestIds } = pickMainFrameHops([+ docRequest('R1', 'https://ex.com/a', ''),+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),+ docRequest('R2', 'https://ex.com/b', ''),+ loadingFailed('R2', 'net::ERR_ABORTED'),+ ]);+ expect(mainRequestIds).toEqual(['R1', 'R2']);+ expect(pendingMainRequestIds).toEqual([]);+ });++ it('names each pending navigation by its latest requested URL (redirects included)', () => {+ const { pendingMainRequestIds, pendingMainRequestUrls } = pickMainFrameHops([+ docRequest('R1', 'https://ex.com/a', ''),+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),+ docRequest('R2', 'https://ex.com/b', ''),+ // R2 redirected before stalling: the refusal must name where it ended up.+ {+ method: 'Network.requestWillBeSent',+ params: {+ requestId: 'R2', loaderId: 'R2', type: 'Document', request: { url: 'https://ex.com/c' },+ redirectResponse: { url: 'https://ex.com/b', remoteIPAddress: '93.184.216.34', status: 302 },+ },+ },+ ]);+ expect(pendingMainRequestIds).toEqual(['R2']);+ expect(pendingMainRequestUrls).toEqual(['https://ex.com/c']);+ });+it('returns no hops when no main-frame document load is present', () => {const { hops, mainRequestIds, finalUrl } = pickMainFrameHops([{ method: 'Network.requestWillBeSent', params: { requestId: 'R2', loaderId: 'R1', type: 'Image', request: { url: 'https://cdn/x.png' } } },@@ -269,13 +306,45 @@ describe('ssrfPinRefusalReason (SSRF pin gate)', () => {expect(reason).toMatch(/disallowed address 127\.0\.0\.1/);});- it('refuses an in-flight top-level navigation (started, no response)', () => {+ it('refuses an in-flight top-level navigation (started, no response), naming its URL', () => {const reason = ssrfPinRefusalReason([docRequest('R1', 'https://ex.com/a'),docResponse('R1', 'https://ex.com/a', '93.184.216.34'),docRequest('R2', 'https://evil.example/x'),], allow, 'https://ex.com/a');expect(reason).toMatch(/still in flight/);+ // Which navigation was unpinned is the whole diagnostic value — the capture+ // window is gone by the time anyone reads the error.+ expect(reason).toContain('https://evil.example/x');+ });++ // The Stacker News regression: a single-page app supersedes its own in-flight+ // navigation routinely, and the gate counted that dead load as "still in+ // flight" forever, refusing a perfectly clean read at random.+ it('does NOT refuse a top-level navigation Chrome canceled, but DOES refuse one still open', () => {+ const canceled = [+ docRequest('R1', 'https://ex.com/a'),+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),+ docRequest('R2', 'https://ex.com/b'),+ loadingFailed('R2', 'net::ERR_ABORTED'),+ ];+ expect(ssrfPinRefusalReason(canceled, allow, 'https://ex.com/a')).toBeNull();++ const reason = ssrfPinRefusalReason([...canceled, docRequest('R3', 'https://ex.com/c')], allow, 'https://ex.com/a');+ expect(reason).toMatch(/still in flight/);+ expect(reason).toContain('https://ex.com/c');+ expect(reason).not.toContain('https://ex.com/b');+ });++ // A failure that lands AFTER the response (a truncated body) must not undo the+ // pin: that hop was already verified and its IP still has to pass.+ it('keeps verifying a hop whose body failed after the response was received', () => {+ const reason = ssrfPinRefusalReason([+ docRequest('R1', 'http://127.0.0.1/x'),+ docResponse('R1', 'http://127.0.0.1/x', '127.0.0.1'),+ loadingFailed('R1', 'net::ERR_CONNECTION_RESET'),+ ], allow, 'http://127.0.0.1/x');+ expect(reason).toMatch(/disallowed address 127\.0\.0\.1/);});it('refuses when no main-frame document response was observed', () => {diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.jsindex acc36d9c22..7d381486d1 100644--- a/server/services/catalogIngestSources.js+++ b/server/services/catalogIngestSources.js@@ -31,6 +31,7 @@ import * as brainStorage from './brainStorage.js';import { extractIngredientsForScrap } from './catalogExtraction.js';import { transcribe } from './voice/stt.js';import {+ closeCdpPage,navigateToUrlPinned,} from './browserService.js';import { lookup } from 'dns/promises';@@ -138,6 +139,10 @@ export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {})evaluateExpression: expression,});+ // The read already happened on that CDP session, so this tab is scratch —+ // every ingested URL would otherwise leave one open in the user's browser.+ await closeCdpPage(page.id);+const parsed = page.evalResult ? safeJSONParse(page.evalResult, null) : null;const text = clampText(parsed?.text || '');if (!text.trim()) throw new Error('no readable text extracted from page');diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.jsindex fe22625843..1f49dcc688 100644--- a/server/services/catalogIngestSources.test.js+++ b/server/services/catalogIngestSources.test.js@@ -33,6 +33,7 @@ vi.mock('./voice/stt.js', () => ({}));vi.mock('./browserService.js', () => ({navigateToUrlPinned: vi.fn(),+ closeCdpPage: vi.fn(),}));vi.mock('fs/promises', () => ({writeFile: vi.fn(),@@ -117,6 +118,9 @@ describe('fetchUrlMainText', () => {'https://ex.com/a',expect.objectContaining({ verifyRemoteIp: expect.any(Function), evaluateExpression: expect.any(String) }),);+ // The read ran on that session, so the tab is scratch — every ingested URL+ // would otherwise leave one open in the user's browser.+ expect(browserService.closeCdpPage).toHaveBeenCalledWith('p1');});it('throws when the page extracts no readable text', async () => {diff --git a/server/services/stackerNewsBrowser.js b/server/services/stackerNewsBrowser.jsindex f1c02d452b..f4890c6885 100644--- a/server/services/stackerNewsBrowser.js+++ b/server/services/stackerNewsBrowser.js@@ -1,5 +1,5 @@import { isPrivateAddress } from '../lib/safeUrlFetch.js';-import { navigateToUrlPinned } from './browserService.js';+import { closeCdpPage, navigateToUrlPinned } from './browserService.js';const ORIGIN = 'https://stacker.news';// The ONE signed-in-identity extractor. Both the handoff identity check and the@@ -41,8 +41,13 @@ export async function getStackerNewsBrowserIdentity() {settleMs: 1_000,evaluateExpression: STACKER_NEWS_IDENTITY_EXPRESSION,});+ // The identity tab is scratch, like the read transport's (browserReader.js):+ // it is read and torn down. Only a handoff leaves a tab for the user, so+ // without this every "Check browser identity" click — and every handoff, which+ // checks identity first — piled another stacker.news tab into their browser.+ await closeCdpPage(page.id);verifyFinalOrigin(page.url);- return { username: page.evalResult?.username || null, pageId: page.id, url: page.url };+ return { username: page.evalResult?.username || null, url: page.url };}export async function openStackerNewsHandoff({ kind, value, expectedUsername }) {diff --git a/server/services/stackerNewsBrowser.test.js b/server/services/stackerNewsBrowser.test.jsindex b6e099af26..d64e6908e5 100644--- a/server/services/stackerNewsBrowser.test.js+++ b/server/services/stackerNewsBrowser.test.js@@ -1,11 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const navigateToUrlPinned = vi.fn();-vi.mock('./browserService.js', () => ({ navigateToUrlPinned }));-const { openStackerNewsHandoff } = await import('./stackerNewsBrowser.js');+const closeCdpPage = vi.fn();+vi.mock('./browserService.js', () => ({ navigateToUrlPinned, closeCdpPage }));+const { getStackerNewsBrowserIdentity, openStackerNewsHandoff } = await import('./stackerNewsBrowser.js');describe('Stacker News CDP handoff', () => {- beforeEach(() => navigateToUrlPinned.mockReset());+ beforeEach(() => { navigateToUrlPinned.mockReset(); closeCdpPage.mockReset(); });it('uses fixed Stacker News URLs and blocks an identity mismatch before opening a destination', async () => {navigateToUrlPinned.mockResolvedValue({ id: 'page-1', url: 'https://stacker.news', evalResult: { username: 'wrong_user' } });@@ -23,4 +24,20 @@ describe('Stacker News CDP handoff', () => {expect(navigateToUrlPinned.mock.calls[1][0]).toBe('https://stacker.news/items/42');expect(navigateToUrlPinned.mock.calls[1][1]).not.toHaveProperty('evaluateExpression');});++ // The identity read is scratch: without teardown every check (and every+ // handoff, which checks first) leaves another stacker.news tab behind.+ it('tears the identity tab down and leaves ONLY the handoff tab open', async () => {+ navigateToUrlPinned+ .mockResolvedValueOnce({ id: 'identity', url: 'https://stacker.news', evalResult: { username: 'example_user' } })+ .mockResolvedValueOnce({ id: 'item', url: 'https://stacker.news/items/42' });+ await openStackerNewsHandoff({ kind: 'item', value: '42', expectedUsername: 'example_user' });+ expect(closeCdpPage.mock.calls).toEqual([['identity']]);+ });++ it('closes the identity tab on a standalone identity check', async () => {+ navigateToUrlPinned.mockResolvedValue({ id: 'identity', url: 'https://stacker.news', evalResult: { username: 'example_user' } });+ await expect(getStackerNewsBrowserIdentity()).resolves.toEqual({ username: 'example_user', url: 'https://stacker.news' });+ expect(closeCdpPage).toHaveBeenCalledWith('identity');+ });});