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
fix: fail loudly on a failed browser extraction and keep key-bearing accounts on API reads (#3318)
[._.]/ Adam Eivyb35abbe75ccd
diff --git a/server/integrations/stackerNews/browserReader.js b/server/integrations/stackerNews/browserReader.jsindex 70077a27e6..de811da96f 100644--- a/server/integrations/stackerNews/browserReader.js+++ b/server/integrations/stackerNews/browserReader.js@@ -16,7 +16,7 @@// same hashing, same `inspectUntrustedContent` treatment, same columns.import { isPrivateAddress } from '../../lib/safeUrlFetch.js';import { closeCdpPage, navigateToUrlPinned } from '../../services/browserService.js';-import { stackerNewsBrowserOrigin as ORIGIN, verifyFinalOrigin } from '../../services/stackerNewsBrowser.js';+import { STACKER_NEWS_IDENTITY_EXPRESSION, stackerNewsBrowserOrigin as ORIGIN, verifyFinalOrigin } from '../../services/stackerNewsBrowser.js';const SETTLE_MS = 1_500;const MAX_ITEMS_PER_PAGE = 100;@@ -43,30 +43,30 @@ const itemsUrl = (slug, cursor) => {return url.toString();};-const ME_EXPRESSION = `(() => {- const raw = document.querySelector('#__NEXT_DATA__')?.textContent;- if (!raw) return null;- const props = JSON.parse(raw)?.props;- const me = props?.pageProps?.me || props?.me;- if (!me || typeof me.name !== 'string') return null;- return { id: me.id == null ? null : String(me.id), name: me.name };-})()`;-+// Every expression returns `null` ONLY when extraction itself failed (no+// `#__NEXT_DATA__`, or Stacker News moved the server-rendered payload) so+// `readPage` can throw. A successful extraction that simply found no territory+// returns `{ sub: null }` — "nothing there" must never look like "we could not+// look", or a sync would clear `last_error` and advance `last_sync_at` after+// silently ingesting nothing.const SUB_EXPRESSION = `(() => {const raw = document.querySelector('#__NEXT_DATA__')?.textContent;if (!raw) return null;const props = JSON.parse(raw)?.props?.pageProps;- const sub = props?.ssrData?.sub || props?.sub;- if (!sub || typeof sub.name !== 'string') return null;+ if (!props) return null;+ const sub = props.ssrData?.sub || props.sub;+ if (!sub || typeof sub.name !== 'string') return { sub: null };return {- name: sub.name,- userId: sub.userId == null ? null : String(sub.userId),- baseCost: sub.baseCost ?? null,- postsSatsFilter: sub.postsSatsFilter ?? null,- replyCost: sub.replyCost ?? null,- postTypes: Array.isArray(sub.postTypes) ? sub.postTypes.map((type) => String(type)) : [],- status: sub.status == null ? null : String(sub.status),- nsfw: Boolean(sub.nsfw),+ sub: {+ name: sub.name,+ userId: sub.userId == null ? null : String(sub.userId),+ baseCost: sub.baseCost ?? null,+ postsSatsFilter: sub.postsSatsFilter ?? null,+ replyCost: sub.replyCost ?? null,+ postTypes: Array.isArray(sub.postTypes) ? sub.postTypes.map((type) => String(type)) : [],+ status: sub.status == null ? null : String(sub.status),+ nsfw: Boolean(sub.nsfw),+ },};})()`;@@ -77,21 +77,25 @@ const ITEMS_EXPRESSION = `(() => {const raw = document.querySelector('#__NEXT_DATA__')?.textContent;if (!raw) return null;const page = JSON.parse(raw)?.props?.pageProps?.ssrData?.items;- if (!page) return null;+ // The /recent page always server-renders this list, so its absence means the+ // extraction failed rather than that the territory is empty.+ if (!page || !Array.isArray(page.items)) return null;const str = (value, max) => typeof value === 'string' ? value.slice(0, max) : '';return {- cursor: typeof page.cursor === 'string' ? page.cursor.slice(0, ${MAX_CURSOR_LENGTH}) : null,- items: (Array.isArray(page.items) ? page.items : []).slice(0, ${MAX_ITEMS_PER_PAGE}).map((item) => ({- id: item?.id == null ? null : String(item.id),- createdAt: str(item?.createdAt, 64) || null,- updatedAt: str(item?.updatedAt, 64) || null,- title: str(item?.title, ${MAX_TITLE_LENGTH}),- text: str(item?.text, ${MAX_TEXT_LENGTH}),- url: str(item?.url, 2000),- parentId: item?.parentId == null ? null : String(item.parentId),- user: { name: str(item?.user?.name, 120) },- subName: str(item?.subName, 120),- })),+ items: {+ cursor: typeof page.cursor === 'string' ? page.cursor.slice(0, ${MAX_CURSOR_LENGTH}) : null,+ items: page.items.slice(0, ${MAX_ITEMS_PER_PAGE}).map((item) => ({+ id: item?.id ?? null,+ createdAt: str(item?.createdAt, 64) || null,+ updatedAt: str(item?.updatedAt, 64) || null,+ title: str(item?.title, ${MAX_TITLE_LENGTH}),+ text: str(item?.text, ${MAX_TEXT_LENGTH}),+ url: str(item?.url, 2000),+ parentId: item?.parentId ?? null,+ user: { name: str(item?.user?.name, 120) },+ subName: str(item?.subName, 120),+ })),+ },};})()`;@@ -107,7 +111,11 @@ async function readPage(url, evaluateExpression) {const originError = await Promise.resolve(page.url).then(verifyFinalOrigin).then(() => null, (error) => error);await closeCdpPage(page.id);if (originError) throw originError;- return page.evalResult ?? null;+ // Null means the extractor found no server-rendered payload, or `Runtime.evaluate`+ // itself threw. Fail loudly: a swallowed extraction failure would look like a+ // clean empty sync and quietly stop monitoring.+ if (page.evalResult == null) throw new Error('Could not read Stacker News data from the pinned browser page');+ return page.evalResult;}// Numbers are accepted and stringified because Stacker News serves numeric IDs@@ -129,32 +137,39 @@ const normalizeItemsPage = (page) => ({cursor: nullableString(page?.cursor, MAX_CURSOR_LENGTH),items: (Array.isArray(page?.items) ? page.items : []).slice(0, MAX_ITEMS_PER_PAGE)- .filter((item) => item?.id != null && String(item.id).length).map((item) => ({- id: boundedString(String(item.id), 200),- createdAt: nullableString(item.createdAt, 64),- updatedAt: nullableString(item.updatedAt, 64),- title: boundedString(item.title, MAX_TITLE_LENGTH),- text: boundedString(item.text, MAX_TEXT_LENGTH),- url: boundedString(item.url, 2_000),- parentId: nullableString(item.parentId, 200),- user: { name: boundedString(item.user?.name, 120) },- subName: boundedString(item.subName, 120),- })),+ // `boundedString` rejects anything that is not a string or finite number,+ // so an id of `true` / `{}` normalizes to '' and the item is dropped below+ // rather than ingested as "true" / "[object Object]".+ id: boundedString(item?.id, 200),+ createdAt: nullableString(item?.createdAt, 64),+ updatedAt: nullableString(item?.updatedAt, 64),+ title: boundedString(item?.title, MAX_TITLE_LENGTH),+ text: boundedString(item?.text, MAX_TEXT_LENGTH),+ url: boundedString(item?.url, 2_000),+ parentId: nullableString(item?.parentId, 200),+ user: { name: boundedString(item?.user?.name, 120) },+ subName: boundedString(item?.subName, 120),+ }))+ .filter((item) => item.id),});export async function readMe() {- const me = await readPage(ORIGIN, ME_EXPRESSION);- if (!me?.name) throw new Error('The pinned browser is not signed in to Stacker News');- return { me: { id: nullableString(me.id, 200), name: boundedString(me.name, 120) } };+ // Shares the handoff's identity extractor, so "Check browser identity" and a+ // keyless sync can never disagree about who is signed in.+ const identity = await readPage(ORIGIN, STACKER_NEWS_IDENTITY_EXPRESSION);+ const name = boundedString(identity?.username, 120);+ if (!name) throw new Error('The pinned browser is not signed in to Stacker News');+ return { me: { id: nullableString(identity.id, 200), name } };}export async function readSub(slug) {- const sub = await readPage(slugPath(slug), SUB_EXPRESSION);- if (!sub?.name) return { sub: null };+ const { sub } = await readPage(slugPath(slug), SUB_EXPRESSION);+ const name = boundedString(sub?.name, 120);+ if (!name) return { sub: null };return {sub: {- name: boundedString(sub.name, 120),+ name,userId: nullableString(sub.userId, 200),baseCost: Number.isFinite(sub.baseCost) ? sub.baseCost : null,postsSatsFilter: Number.isFinite(sub.postsSatsFilter) ? sub.postsSatsFilter : null,@@ -167,8 +182,8 @@ export async function readSub(slug) {}export async function readItems(slug, cursor = null) {- const page = await readPage(itemsUrl(slug, cursor), ITEMS_EXPRESSION);- return { items: normalizeItemsPage(page) };+ const { items } = await readPage(itemsUrl(slug, cursor), ITEMS_EXPRESSION);+ return { items: normalizeItemsPage(items) };}const BROWSER_READS = Object.freeze({diff --git a/server/integrations/stackerNews/browserReader.test.js b/server/integrations/stackerNews/browserReader.test.jsindex eb9fb2cead..5f86b7375b 100644--- a/server/integrations/stackerNews/browserReader.test.js+++ b/server/integrations/stackerNews/browserReader.test.js@@ -14,22 +14,32 @@ describe('Stacker News browser read transport', () => {});it('reads the signed-in identity from the fixed origin and normalizes to the API shape', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { id: 77, name: 'example_user' }));+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { username: 'example_user', id: '77' }));await expect(readMe()).resolves.toEqual({ me: { id: '77', name: 'example_user' } });expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://stacker.news');expect(navigateToUrlPinned.mock.calls[0][1].evaluateExpression).toContain('__NEXT_DATA__');expect(closeCdpPage).toHaveBeenCalledWith('page-1');});+ // The identity extractor is shared with the handoff's "Check browser identity"+ // so the two can never disagree — including its profile-link fallback, which+ // yields a username but no user ID.+ it('accepts the shared extractor profile-link fallback, with no user ID to verify ownership against', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { username: 'example_user', id: null }));+ await expect(readMe()).resolves.toEqual({ me: { id: null, name: 'example_user' } });+ });+it('throws when the pinned browser is not signed in', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', null));+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { username: null, id: null }));await expect(readMe()).rejects.toThrow('not signed in');});it('builds only the fixed territory URL and normalizes the sub selection', async () => {navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', {- name: 'example', userId: 42, baseCost: 1, replyCost: 1, postsSatsFilter: 0,- postTypes: ['LINK', 'DISCUSSION'], status: 'ACTIVE', nsfw: false,+ sub: {+ name: 'example', userId: 42, baseCost: 1, replyCost: 1, postsSatsFilter: 0,+ postTypes: ['LINK', 'DISCUSSION'], status: 'ACTIVE', nsfw: false,+ },}));await expect(readSub('example')).resolves.toEqual({sub: { name: 'example', userId: '42', baseCost: 1, postsSatsFilter: 0, replyCost: 1, postTypes: ['LINK', 'DISCUSSION'], status: 'ACTIVE', nsfw: false },@@ -37,15 +47,17 @@ describe('Stacker News browser read transport', () => {expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://stacker.news/~example/recent');});- it('reports a missing territory as a null sub rather than throwing', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~ghost/recent', null));+ it('reports a territory the page does not know about as a null sub rather than throwing', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~ghost/recent', { sub: null }));await expect(readSub('ghost')).resolves.toEqual({ sub: null });});it('carries the cursor into the fixed URL and back out of the items page', async () => {navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent?cursor=page-2', {- cursor: 'page-3',- items: [{ id: 42, createdAt: '2026-01-01T00:00:00Z', updatedAt: null, title: 'Example work', text: 'A post', url: '', parentId: null, user: { name: 'example_artist' }, subName: 'example' }],+ items: {+ cursor: 'page-3',+ items: [{ id: 42, createdAt: '2026-01-01T00:00:00Z', updatedAt: null, title: 'Example work', text: 'A post', url: '', parentId: null, user: { name: 'example_artist' }, subName: 'example' }],+ },}));await expect(readItems('example', 'page-2')).resolves.toEqual({items: {@@ -57,18 +69,31 @@ describe('Stacker News browser read transport', () => {});it('omits the cursor parameter on the first page', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', { cursor: null, items: [] }));+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', { items: { cursor: null, items: [] } }));await expect(readItems('example')).resolves.toEqual({ items: { cursor: null, items: [] } });expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://stacker.news/~example/recent');});+ // A failed extraction must never look like a quiet empty page: sync would+ // clear last_error and advance last_sync_at while ingesting nothing.+ it('throws when the page yielded no extractable payload instead of reporting an empty page', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', null));+ await expect(readItems('example')).rejects.toThrow('Could not read Stacker News data');+ await expect(readSub('example')).rejects.toThrow('Could not read Stacker News data');+ await expect(readMe()).rejects.toThrow('Could not read Stacker News data');+ });+it('re-normalizes whatever the untrusted page returned instead of trusting its projection', async () => {navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', {- cursor: { evil: true },- items: [- { id: null, title: 'dropped: no id' },- { id: 7, title: { evil: true }, text: null, user: null, parentId: 9 },- ],+ items: {+ cursor: { evil: true },+ items: [+ { id: null, title: 'dropped: no id' },+ { id: true, title: 'dropped: an id that is not a string or number' },+ { id: { toString: 'nope' }, title: 'dropped: object id' },+ { id: 7, title: { evil: true }, text: null, user: null, parentId: 9 },+ ],+ },}));await expect(readItems('example')).resolves.toEqual({items: {@@ -79,7 +104,7 @@ describe('Stacker News browser read transport', () => {});it('refuses a navigation that landed off the fixed origin, and still closes the tab', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://example.com/~example/recent', { cursor: null, items: [] }));+ navigateToUrlPinned.mockResolvedValue(page('https://example.com/~example/recent', { items: { cursor: null, items: [] } }));await expect(readItems('example')).rejects.toThrow('left the fixed origin');expect(closeCdpPage).toHaveBeenCalledWith('page-1');});@@ -91,7 +116,7 @@ describe('Stacker News browser read transport', () => {});it('dispatches named operations with the same envelope as the GraphQL transport', async () => {- navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { id: '1', name: 'example_user' }));+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { username: 'example_user', id: '1' }));await expect(executeStackerNewsBrowserRead('me')).resolves.toEqual({ me: { id: '1', name: 'example_user' } });await expect(executeStackerNewsBrowserRead('nope')).rejects.toThrow('Unsupported Stacker News browser read');});diff --git a/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.js b/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.jsnew file mode 100644index 0000000000..7a5b408e18--- /dev/null+++ b/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.js@@ -0,0 +1,19 @@+/**+ * `read_transport` was added with a `'browser'` default so a fresh account works+ * without an API key (#3318). Applied blindly that would flip every EXISTING+ * account — all of which necessarily have a stored key, because nothing else+ * worked before — onto browser reads, breaking any scheduled sync whose pinned+ * Chrome is not signed in to Stacker News.+ *+ * Pin only the accounts that already hold a credential to the transport they+ * were actually using. Runs exactly once, so an account the user later switches+ * to browser reads stays switched.+ */+export async function up(client) {+ await client.query(+ `UPDATE stacker_news_accounts a+ SET read_transport='api',updated_at=NOW()+ WHERE a.read_transport='browser'+ AND EXISTS (SELECT 1 FROM stacker_news_credentials c WHERE c.account_id=a.id)`,+ );+}diff --git a/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.test.js b/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.test.jsnew file mode 100644index 0000000000..38e413302d--- /dev/null+++ b/server/scripts/db-migrations/006-stacker-news-existing-key-accounts-keep-api-reads.test.js@@ -0,0 +1,15 @@+import { describe, expect, it, vi } from 'vitest';+import { up } from './006-stacker-news-existing-key-accounts-keep-api-reads.js';++describe('Stacker News existing-key read transport migration', () => {+ it('pins only credential-bearing accounts to API reads, leaving keyless ones on the browser default', async () => {+ const query = vi.fn(async () => ({ rows: [] }));+ await up({ query });+ const [sql] = query.mock.calls[0];+ expect(sql).toContain("SET read_transport='api'");+ expect(sql).toContain('FROM stacker_news_credentials');+ // Scoped to the default so a re-run (or a later user choice) cannot undo an+ // explicit switch back to browser reads.+ expect(sql).toContain("a.read_transport='browser'");+ });+});diff --git a/server/services/stackerNewsBrowser.js b/server/services/stackerNewsBrowser.jsindex 79c2973da8..f1c02d452b 100644--- a/server/services/stackerNewsBrowser.js+++ b/server/services/stackerNewsBrowser.js@@ -2,18 +2,23 @@ import { isPrivateAddress } from '../lib/safeUrlFetch.js';import { navigateToUrlPinned } from './browserService.js';const ORIGIN = 'https://stacker.news';-const IDENTITY_EXPRESSION = `(() => {+// The ONE signed-in-identity extractor. Both the handoff identity check and the+// browser read transport (integrations/stackerNews/browserReader.js) run it, so+// they can never disagree about who the pinned browser is signed in as. `id` is+// null on the profile-link fallback — ownership verification then fails closed+// rather than matching a territory owner it could not confirm.+export const STACKER_NEWS_IDENTITY_EXPRESSION = `(() => {const data = document.querySelector('#__NEXT_DATA__')?.textContent;if (data) {const parsed = JSON.parse(data);const me = parsed?.props?.pageProps?.me || parsed?.props?.me;- if (typeof me?.name === 'string') return { username: me.name };+ if (typeof me?.name === 'string') return { username: me.name, id: me.id == null ? null : String(me.id) };}const link = [...document.querySelectorAll('a[href]')].find((node) => {const href = node.getAttribute('href') || '';return node.getAttribute('aria-label')?.toLowerCase().includes('profile') && /^\\\/[a-zA-Z0-9_-]+$/.test(href);});- return { username: link ? link.getAttribute('href').slice(1) : null };+ return { username: link ? link.getAttribute('href').slice(1) : null, id: null };})()`;const fixedUrl = (kind, value) => {@@ -34,7 +39,7 @@ export async function getStackerNewsBrowserIdentity() {const page = await navigateToUrlPinned(ORIGIN, {verifyRemoteIp: (ip) => !isPrivateAddress(ip),settleMs: 1_000,- evaluateExpression: IDENTITY_EXPRESSION,+ evaluateExpression: STACKER_NEWS_IDENTITY_EXPRESSION,});verifyFinalOrigin(page.url);return { username: page.evalResult?.username || null, pageId: page.id, url: page.url };