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
feat: read Stacker News through the signed-in pinned browser so sync works without a key (#3318)
[._.]/ Adam Eivyaf43d4cb2039
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ef1dae217a..887911e404 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -135,6 +135,10 @@- **[issue-3311] A collection now records who created it instead of the grid guessing from its name.** The "auto-generated" ordering and badge shipped in #3283 reverse-engineered provenance on the client from four independent clues — a name prefix, an `Auto-…` description, a `uc-`/`sc-` id, or a universe/series link — so every new machine-created bucket quietly sorted as if you had made it yourself until someone remembered to extend that list. Collections are now stamped `auto` or `user` when they are created, existing ones were classified once by a migration, and the old clue-matching only runs for a record a peer on an older version has not stamped yet.- **[issue-3312] The "file this into a collection" picker got the same treatment as the grid.** The popover you actually use to file an image or video still listed every collection in raw order with the full prefixed name in each row, so filing something meant scrolling a wall of identical `Creative Director: …` entries in a 240px-wide dropdown. Rows now use the same ordering as `/media/collections` — collections holding something sort above the auto-generated empties — and each row lifts the shared creator prefix into a small badge so the part of the name that tells them apart gets the full row width. Search matches its words in any order instead of demanding one contiguous substring. Empty collections are still listed, since filing *into* an empty collection is the whole point.+## Stacker News++- **[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 on request 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 new 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. Accounts carry a **Read transport** setting (browser by default) so anyone who does hold a key can keep using it, and the key itself is now labelled optional and needed only for reviewed publishing — which still requires it and still refuses without one. The **Check API identity** button is disabled with an explanation when no key is stored instead of failing with a bare error.+## UI Consistency- **[issue-3319] Stacker News now says which account you are looking at, on every tab.** Territories, monitored items, and queued actions were always filtered to the selected account, but nothing on screen said so — the only hint was a small grey `@username` in the header, and the account list lived on the Accounts tab, so switching accounts meant leaving whatever you were working in. The header now carries an account switcher that works from any tab and keeps you on it, and every scoped heading and empty state names the account: "Communities for @…", "Approval queue for @…", "Add community to @…". The account form — nineteen fields that used to render twice at once, side by side, in one flat scroll — moved into the shared drawer, grouped into Identity, Monitoring & models, Stewardship, and Budgets tabs with the open tab kept in the URL. Because the drawer unmounts inactive tabs, Save re-validates every field itself and jumps to the tab holding the bad one instead of letting an emptied number box through as a zero.diff --git a/client/src/pages/StackerNews.jsx b/client/src/pages/StackerNews.jsxindex c05493e913..37b0a55528 100644--- a/client/src/pages/StackerNews.jsx+++ b/client/src/pages/StackerNews.jsx@@ -55,7 +55,7 @@ const validateAccountForm = (form) => {});return invalid ? { tab: invalid.tab, message: `${invalid.label} must be a whole number from ${invalid.min} to ${invalid.max}.` } : null;};-const emptyAccount = { label: '', username: '', apiKey: '', clearApiKey: false, enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 30, analysisEnabled: false, textModel: '', visionModel: '', guidance: '', tone: '', allowedThemes: '', disallowedThemes: '', escalationCues: '', desiredEngagement: '', maxPerHour: 3, maxPerDay: 12, minMinutesBetween: 5 };+const emptyAccount = { label: '', username: '', apiKey: '', clearApiKey: false, readTransport: 'browser', enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 30, analysisEnabled: false, textModel: '', visionModel: '', guidance: '', tone: '', allowedThemes: '', disallowedThemes: '', escalationCues: '', desiredEngagement: '', maxPerHour: 3, maxPerDay: 12, minMinutesBetween: 5 };const emptyTerritory = { slug: '', label: '', isOwned: false, monitoringEnabled: '', inheritAccountRules: true, guidance: '', tone: '', allowedThemes: '', disallowedThemes: '', escalationCues: '' };const emptyDraft = { kind: 'publish_comment', itemId: '', territoryId: '', title: '', body: '', destination: 'item' };const fieldClass = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white';@@ -73,7 +73,8 @@ const territoryPayload = (form) => ({rules: territoryRules(form),});const accountToForm = (account) => ({- label: account.label, username: account.username, apiKey: '', clearApiKey: false, enabled: account.enabled,+ label: account.label, username: account.username, apiKey: '', clearApiKey: false,+ readTransport: account.readTransport || 'browser', enabled: account.enabled,monitoringEnabled: account.monitoringEnabled, monitoringIntervalMinutes: account.monitoringIntervalMinutes,analysisEnabled: account.analysisEnabled, textModel: account.textModel, visionModel: account.visionModel,guidance: account.rules?.guidance || '', tone: account.rules?.tone || '', allowedThemes: (account.rules?.allowedThemes || []).join(', '),@@ -235,6 +236,7 @@ export default function StackerNews() {if (rejectInvalidAccount(newAccount)) return;finish('create-account', api.createStackerNewsAccount({label: newAccount.label, username: newAccount.username, enabled: newAccount.enabled, ...(newAccount.apiKey ? { apiKey: newAccount.apiKey } : {}),+ readTransport: newAccount.readTransport,monitoringEnabled: newAccount.monitoringEnabled, monitoringIntervalMinutes: Number(newAccount.monitoringIntervalMinutes),analysisEnabled: newAccount.analysisEnabled, textModel: newAccount.textModel, visionModel: newAccount.visionModel,rules: accountRules(newAccount),@@ -251,6 +253,7 @@ export default function StackerNews() {finish('save-account', api.updateStackerNewsAccount(savedAccountId, {label: editAccount.label, username: editAccount.username, enabled: editAccount.enabled,...(editAccount.clearApiKey ? { apiKey: '' } : editAccount.apiKey ? { apiKey: editAccount.apiKey } : {}),+ readTransport: editAccount.readTransport,monitoringEnabled: editAccount.monitoringEnabled, monitoringIntervalMinutes: Number(editAccount.monitoringIntervalMinutes),analysisEnabled: editAccount.analysisEnabled, textModel: editAccount.textModel, visionModel: editAccount.visionModel,rules: accountRules(editAccount),@@ -292,14 +295,14 @@ export default function StackerNews() {setNotice('Community removed.');});- const checkConnection = () => selected && finish('verify', api.verifyStackerNewsAccount(selected.id, { silent: true }), (result) => {+ const checkConnection = () => selected && finish('verify', api.verifyStackerNewsAccount(selected.id, 'api', { silent: true }), (result) => {setNotice(!result.connected ? 'Add an API key before testing.' : `API identity: @${result.username}. ${result.matchesConfigured ? 'Matches this account.' : 'Mismatch: writes are blocked.'}`);});const checkBrowser = () => selected && finish('browser', api.getStackerNewsBrowserIdentity(selected.id, { silent: true }), (result) => {setNotice(`Pinned browser identity: @${result.username || 'unknown'}. ${result.matchesConfigured ? 'Matches this account.' : 'Mismatch: handoffs are blocked.'}`);});const syncNow = () => selected && finish('sync', api.syncStackerNewsAccount(selected.id, { silent: true }), async (result) => {- setNotice(`Sync complete: ${result.ingested} item(s), ${result.analyzed} analyzed.`); await Promise.all([loadAccounts(), loadSelected()]);+ setNotice(`Sync complete via ${result.transport === 'api' ? 'the API key' : 'the pinned browser'}: ${result.ingested} item(s), ${result.analyzed} analyzed.`); await Promise.all([loadAccounts(), loadSelected()]);});const analyze = (item) => finish(`analyze-${item.id}`, api.analyzeStackerNewsItem(item.id, { silent: true }), (result) => {setAnalysisResults((previous) => ({ ...previous, [item.id]: result }));@@ -411,10 +414,13 @@ export default function StackerNews() {{selected ? (<section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Settings and safety for {scope}</h2>- <p className="mt-1 text-sm text-gray-400">{selected.label} · {selected.monitoringEnabled ? `monitored every ${selected.monitoringIntervalMinutes}m` : 'monitoring off'} · {selected.apiKeyConfigured ? 'API key stored' : 'no API key stored'}</p>+ <p className="mt-1 text-sm text-gray-400">{selected.label} · {selected.monitoringEnabled ? `monitored every ${selected.monitoringIntervalMinutes}m` : 'monitoring off'} · reads via {selected.readTransport === 'api' ? 'API key' : 'pinned browser'} · {selected.apiKeyConfigured ? 'API key stored' : 'no API key stored'}</p><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={buttonClass} onClick={() => openAccountForm('edit')}>Edit account settings</button>- <button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkConnection}>Check API identity</button>+ {/* The API check is the one action that genuinely needs a stored+ key; reads and the browser check do not. Disable it with a+ reason rather than letting it fail with a bare error. */}+ <button type="button" className={secondaryButton} disabled={accountActionsDisabled || !selected.apiKeyConfigured} title={selected.apiKeyConfigured ? 'Test the stored API key against Stacker News' : 'No API key stored. Reads use the signed-in pinned browser; a key is only needed for reviewed publishing.'} onClick={checkConnection}>Check API identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={checkBrowser}>Check browser identity</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={syncNow}>Sync now</button></div>@@ -511,7 +517,17 @@ function AccountDrawer({ mode, username, activeTab, onTabChange, onClose, formEr{activeTab === 'identity' && <><Field id={`${prefix}-label`} label="Local label"><input id={`${prefix}-label`} required className={fieldClass} value={form.label} onChange={(event) => update('label', event.target.value)} /></Field><Field id={`${prefix}-username`} label="Stacker News username"><input id={`${prefix}-username`} required className={fieldClass} value={form.username} onChange={(event) => update('username', event.target.value)} /></Field>- <Field id={`${prefix}-api-key`} label={isNew ? 'API key (optional)' : 'Replace API key (leave blank to keep)'}><input id={`${prefix}-api-key`} type="password" className={fieldClass} disabled={form.clearApiKey} value={form.apiKey} onChange={(event) => update('apiKey', event.target.value)} /></Field>+ <Field id={`${prefix}-read-transport`} label="Read transport">+ <select id={`${prefix}-read-transport`} className={fieldClass} value={form.readTransport} onChange={(event) => update('readTransport', event.target.value)}>+ <option value="browser">Signed-in pinned browser (no key needed)</option>+ <option value="api">Stacker News API key</option>+ </select>+ <p className="mt-1 text-xs text-gray-400">Identity checks and syncs read through the pinned browser by default. Choose the API only if a key is stored.</p>+ </Field>+ <Field id={`${prefix}-api-key`} label={isNew ? 'API key (optional)' : 'Replace API key (leave blank to keep)'}>+ <input id={`${prefix}-api-key`} type="password" className={fieldClass} disabled={form.clearApiKey} value={form.apiKey} onChange={(event) => update('apiKey', event.target.value)} />+ <p className="mt-1 text-xs text-gray-400">Optional. Stacker News grants API keys on request only — there is no self-serve setting — so PortOS needs one just for reviewed publishing, never for reads.</p>+ </Field>{canClearCredential && checkbox('clearApiKey', 'Remove stored API key when saving')}{checkbox('enabled', 'Account enabled')}</>}diff --git a/client/src/pages/StackerNews.test.jsx b/client/src/pages/StackerNews.test.jsxindex 7b75e35c0c..b8226de11b 100644--- a/client/src/pages/StackerNews.test.jsx+++ b/client/src/pages/StackerNews.test.jsx@@ -40,8 +40,8 @@ const modelSelects = () => ({});const accounts = [- { id: 'a1', label: 'Art steward', username: 'art_steward', enabled: true, monitoringEnabled: true, monitoringIntervalMinutes: 15, analysisEnabled: true, textModel: 'example-text', visionModel: '', rules: { guidance: 'Curate visual work' }, apiKeyConfigured: true },- { id: 'a2', label: 'Personal', username: 'personal_stacker', enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 60, analysisEnabled: false, textModel: '', visionModel: '', rules: { guidance: 'Personal rules' }, apiKeyConfigured: false },+ { id: 'a1', label: 'Art steward', username: 'art_steward', enabled: true, monitoringEnabled: true, monitoringIntervalMinutes: 15, analysisEnabled: true, textModel: 'example-text', visionModel: '', rules: { guidance: 'Curate visual work' }, apiKeyConfigured: true, readTransport: 'api' },+ { id: 'a2', label: 'Personal', username: 'personal_stacker', enabled: true, monitoringEnabled: false, monitoringIntervalMinutes: 60, analysisEnabled: false, textModel: '', visionModel: '', rules: { guidance: 'Personal rules' }, apiKeyConfigured: false, readTransport: 'browser' },];// Surfaces the URL so tests can assert the deep-linkable bits — the selected@@ -229,6 +229,36 @@ describe('StackerNews', () => {expect(intervalField()).toHaveValue(15);});+ // Stacker News grants API keys on request only, so a keyless account is the+ // normal case: the browser-backed actions stay usable and only the API check+ // is disabled — with a reason, not a bare failure.+ it('disables only the API identity check when no key is stored, and explains why', async () => {+ renderPage('/stacker-news/a2/accounts');+ const apiCheck = await screen.findByRole('button', { name: 'Check API identity' });+ expect(apiCheck).toBeDisabled();+ expect(apiCheck).toHaveAttribute('title', expect.stringContaining('pinned browser'));+ expect(screen.getByRole('button', { name: 'Check browser identity' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled();+ expect(screen.getByText(/reads via pinned browser/)).toBeInTheDocument();+ });++ it('forces the API transport from the API identity check', async () => {+ const user = userEvent.setup();+ api.verifyStackerNewsAccount.mockResolvedValue({ configured: true, connected: true, transport: 'api', username: 'art_steward', matchesConfigured: true });+ renderPage('/stacker-news/a1/accounts');+ await user.click(await screen.findByRole('button', { name: 'Check API identity' }));+ await waitFor(() => expect(api.verifyStackerNewsAccount).toHaveBeenCalledWith('a1', 'api', { silent: true }));+ });++ it('saves the chosen read transport with the account', async () => {+ const user = userEvent.setup();+ api.updateStackerNewsAccount.mockResolvedValue({ ...accounts[0], readTransport: 'browser' });+ renderPage('/stacker-news/a1/accounts?snAccount=edit');+ await user.selectOptions(await screen.findByLabelText('Read transport', { selector: '#edit-account-read-transport' }), 'browser');+ await user.click(screen.getByRole('button', { name: 'Save account' }));+ await waitFor(() => expect(api.updateStackerNewsAccount).toHaveBeenCalledWith('a1', expect.objectContaining({ readTransport: 'browser' }), { silent: true }));+ });+it('can explicitly remove a stored API key', async () => {const user = userEvent.setup();api.updateStackerNewsAccount.mockResolvedValue({ ...accounts[0], apiKeyConfigured: false });diff --git a/client/src/services/apiStackerNews.js b/client/src/services/apiStackerNews.jsindex 5494c7c7f1..7f0f144dd6 100644--- a/client/src/services/apiStackerNews.js+++ b/client/src/services/apiStackerNews.js@@ -5,7 +5,9 @@ export const getStackerNewsAccount = (id, options = {}) => request(`/stacker-newexport const createStackerNewsAccount = (data, options = {}) => request('/stacker-news/accounts', { method: 'POST', body: JSON.stringify(data), ...options });export const updateStackerNewsAccount = (id, data, options = {}) => request(`/stacker-news/accounts/${id}`, { method: 'PATCH', body: JSON.stringify(data), ...options });export const deleteStackerNewsAccount = (id, options = {}) => request(`/stacker-news/accounts/${id}`, { method: 'DELETE', ...options });-export const verifyStackerNewsAccount = (id, options = {}) => request(`/stacker-news/accounts/${id}/verify`, { method: 'POST', ...options });+// `transport` forces which read source answers ('api' | 'browser'); omit it to+// use the account's configured read transport.+export const verifyStackerNewsAccount = (id, transport = null, options = {}) => request(`/stacker-news/accounts/${id}/verify`, { method: 'POST', body: JSON.stringify(transport ? { transport } : {}), ...options });export const getStackerNewsBrowserIdentity = (id, options = {}) => request(`/stacker-news/accounts/${id}/browser-identity`, { method: 'POST', ...options });export const syncStackerNewsAccount = (id, options = {}) => request(`/stacker-news/accounts/${id}/sync`, { method: 'POST', ...options });export const getStackerNewsTerritories = (accountId, options = {}) => request(`/stacker-news/accounts/${accountId}/territories`, options);diff --git a/docs/features/stacker-news.md b/docs/features/stacker-news.mdindex 2d0ccd9371..7da509db46 100644--- a/docs/features/stacker-news.md+++ b/docs/features/stacker-news.md@@ -7,13 +7,25 @@ accounts its user explicitly adds.## Safety model+- Reads default to the signed-in pinned browser, so no API key is required to+ verify identity or sync a territory. Stacker News grants API keys on request+ only — there is no self-serve setting — so the key is optional and needed only+ for reviewed publishing.- API keys are encrypted in dedicated credential records, separate from accountconfiguration. They are never returned by the API, logged, placed in modelprompts, or shared with the browser.-- The transport exposes a closed registry of named, typed GraphQL operations at- the fixed Stacker News endpoint. Callers cannot provide GraphQL, endpoints,- headers, or arbitrary variables. Reads may retry transient failures; writes- never retry because that could duplicate content.+- Both read transports are closed registries of named operations. The API+ transport exposes typed GraphQL operations at the fixed Stacker News endpoint;+ the browser transport navigates fixed URLs on the fixed origin and runs fixed+ internal extractors over the page's server-rendered data. Callers name an+ operation and supply a territory slug or cursor — never GraphQL, an endpoint,+ a header, a URL, a selector, or a script. API reads may retry transient+ failures; writes never retry because that could duplicate content.+- A browser read verifies the final URL is still on `https://stacker.news`,+ applies the same public-address pin as every other PortOS navigation, closes+ its scratch tab, and re-normalizes the extracted payload server-side. Browser+ and API items are indistinguishable downstream: same bounding, same content+ hash, same untrusted-content screening, same columns.- Posts, comments, URLs, images, and browser content are untrusted. Text isbounded and screened for instruction-shaped content before optional localanalysis. A prompt-injection match prevents text and images from reaching an@@ -57,6 +69,11 @@ Browser work uses PortOS's existing CDP browser and only fixed primitives:4. open an internally constructed item or territory-settings URL on the samefixed origin.+Browser *reads* use the same primitives with the same constraints: a fixed+`https://stacker.news/~<slug>/recent` URL (plus an opaque `cursor` parameter for+later pages) and a fixed internal extractor. A read closes its tab afterwards; a+handoff leaves its tab open because the open tab is the deliverable.+The API, UI, and models cannot supply a URL, selector, browser script, click, orwallet action. Zap, downzap, boost, and territory-setting work stop at a browserhandoff for the user to complete.@@ -65,9 +82,9 @@ handoff for the user to complete.| Capability | Transport | Automation boundary || --- | --- | --- |-| Verify account identity | Named GraphQL `me` | Read only |-| Refresh territory settings/ownership | Named GraphQL `sub` | Read only |-| Monitor recent posts and comments | Named GraphQL `items` | Explicit sync or an effective account/territory opt-in |+| Verify account identity | Pinned-browser `me` (default) or named GraphQL `me` | Read only |+| Refresh territory settings/ownership | Pinned-browser `sub` (default) or named GraphQL `sub` | Read only |+| Monitor recent posts and comments | Pinned-browser `items` (default) or named GraphQL `items` | Explicit sync or an effective account/territory opt-in || Analyze text/images | Local Ollama | Strict schema; no tools, credentials, or write access || Publish a discussion/comment | Named GraphQL mutations | Separate human approval and execution; no write retry || Open an item or territory settings | Fixed-origin CDP handoff | Identity match required; no clicks or DOM supplied by callers |@@ -80,19 +97,23 @@ handoff for the user to complete.1. Open **Comms > Stacker News > Accounts & Safety** and choose **Add account**.The account form opens in a drawer grouped into Identity, Monitoring & models,Stewardship, and Budgets tabs; the open tab is kept in the URL.-2. Add an API key if API reads or reviewed publishing are needed, then verify- that the returned identity matches the configured username.-3. Add each territory, mark whether the account owns it, and choose whether it+2. Sign the pinned PortOS browser into the same Stacker News account and run+ **Check browser identity**. This is the whole credential step for reads — the+ account's **Read transport** defaults to the pinned browser.+3. Add an API key only if reviewed publishing is needed. Stacker News grants+ keys on request (users post an "[API Key Request]" thread); there is no+ self-serve setting, so PortOS treats the key as optional. With a key stored,+ **Check API identity** verifies it, and the account can be switched to the+ API read transport.+4. Add each territory, mark whether the account owns it, and choose whether itinherits account rules and monitoring. Communities can be edited or removedlater as ownership and stewardship responsibilities change.-4. Configure account and territory guidance, themes, escalation cues, and action+5. Configure account and territory guidance, themes, escalation cues, and actionbudgets. Each account keeps its own effective rules.-5. Optionally choose installed Ollama text and vision models. Analysis remains+6. Optionally choose installed Ollama text and vision models. Analysis remainsoff until explicitly enabled or run on demand.-6. Run **Sync now** once to verify territory ownership and inspect the first+7. Run **Sync now** once to verify territory ownership and inspect the firstsnapshots. Enable a monitoring schedule only when ready.-7. If browser handoffs are needed, sign the pinned PortOS browser into the same- account and run **Check browser identity**.Every tab is scoped to one account. The header carries an account switcher thatkeeps the current tab, and each section names the account it operates on, so adiff --git a/server/integrations/stackerNews/browserReader.js b/server/integrations/stackerNews/browserReader.jsnew file mode 100644index 0000000000..70077a27e6--- /dev/null+++ b/server/integrations/stackerNews/browserReader.js@@ -0,0 +1,191 @@+// Stacker News read transport over the signed-in pinned browser.+//+// Stacker News API keys are not self-serve — the SN team grants them on request+// — so a key-gated read path leaves a normal user unable to sync at all. Every+// field the three named GraphQL reads select is already server-rendered into the+// page's `#__NEXT_DATA__`, so a pinned, origin-verified navigation can produce+// the same data with no key.+//+// Same closed-registry discipline as the GraphQL client: callers name an+// operation and supply a slug/cursor. They never supply a URL, selector, or+// script. URLs are built here from a fixed origin and template; the evaluate+// expressions are module constants with no interpolation.+//+// The returned shapes deliberately mirror `executeStackerNewsOperation`'s so a+// browser-sourced item is indistinguishable downstream from an API-sourced one:+// 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';++const SETTLE_MS = 1_500;+const MAX_ITEMS_PER_PAGE = 100;+const MAX_CURSOR_LENGTH = 400;+const MAX_TEXT_LENGTH = 40_000;+const MAX_TITLE_LENGTH = 2_000;++const slugPath = (slug) => {+ if (typeof slug !== 'string' || !slug.trim() || !/^[a-zA-Z0-9_-]{1,120}$/.test(slug.trim())) {+ throw new Error('Invalid Stacker News territory name');+ }+ return `${ORIGIN}/~${encodeURIComponent(slug.trim())}/recent`;+};++const itemsUrl = (slug, cursor) => {+ const url = new URL(slugPath(slug));+ if (cursor != null) {+ if (typeof cursor !== 'string' || !cursor || cursor.length > MAX_CURSOR_LENGTH) throw new Error('Invalid Stacker News cursor');+ // Stacker News' SSR merges the query string into the page's GraphQL+ // variables, so this is how the second and later pages are requested+ // without a client-side "more" click.+ url.searchParams.set('cursor', 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 };+})()`;++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;+ 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),+ };+})()`;++// Projects in-page so a 21-item SSR payload (each item carries nested sub, user,+// and comment trees) does not cross CDP whole. The server still re-normalizes+// the result below — this projection is a size guard, not the trust boundary.+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;+ 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),+ })),+ };+})()`;++// Every read: pinned navigation, public-address check, origin verification, then+// tear the tab down. Read tabs are scratch — a five-page sync would otherwise+// leave five tabs open in the user's browser per territory.+async function readPage(url, evaluateExpression) {+ const page = await navigateToUrlPinned(url, {+ verifyRemoteIp: (ip) => !isPrivateAddress(ip),+ settleMs: SETTLE_MS,+ 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;+}++// Numbers are accepted and stringified because Stacker News serves numeric IDs+// (item, user, territory owner) and the API transport already stringifies them+// — anything else (object, boolean, null) collapses to absent.+const boundedString = (value, max) => {+ if (typeof value === 'string') return value.slice(0, max);+ return typeof value === 'number' && Number.isFinite(value) ? String(value).slice(0, max) : '';+};+const nullableString = (value, max) => {+ const text = boundedString(value, max);+ return text || null;+};++// Re-normalizes what the page returned. The evaluate expression runs inside an+// untrusted document, so its output is treated as remote data, not as a trusted+// projection — the shape below is what the rest of PortOS is allowed to see.+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),+ })),+});++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) } };+}++export async function readSub(slug) {+ const sub = await readPage(slugPath(slug), SUB_EXPRESSION);+ if (!sub?.name) return { sub: null };+ return {+ sub: {+ name: boundedString(sub.name, 120),+ userId: nullableString(sub.userId, 200),+ baseCost: Number.isFinite(sub.baseCost) ? sub.baseCost : null,+ postsSatsFilter: Number.isFinite(sub.postsSatsFilter) ? sub.postsSatsFilter : null,+ replyCost: Number.isFinite(sub.replyCost) ? sub.replyCost : null,+ postTypes: (Array.isArray(sub.postTypes) ? sub.postTypes : []).slice(0, 20).map((type) => boundedString(type, 40)),+ status: nullableString(sub.status, 40),+ nsfw: Boolean(sub.nsfw),+ },+ };+}++export async function readItems(slug, cursor = null) {+ const page = await readPage(itemsUrl(slug, cursor), ITEMS_EXPRESSION);+ return { items: normalizeItemsPage(page) };+}++const BROWSER_READS = Object.freeze({+ me: () => readMe(),+ sub: ({ name }) => readSub(name),+ items: ({ sub, cursor = null }) => readItems(sub, cursor),+});++/**+ * Transport-shaped sibling of `executeStackerNewsOperation` so callers can pick+ * a transport without branching per operation. Same operation names, same+ * inputs, same returned envelope.+ */+export async function executeStackerNewsBrowserRead(name, input = {}) {+ const read = BROWSER_READS[name];+ if (!read) throw new Error(`Unsupported Stacker News browser read: ${name}`);+ return read(input);+}++export const stackerNewsBrowserReads = Object.freeze(Object.keys(BROWSER_READS));diff --git a/server/integrations/stackerNews/browserReader.test.js b/server/integrations/stackerNews/browserReader.test.jsnew file mode 100644index 0000000000..eb9fb2cead--- /dev/null+++ b/server/integrations/stackerNews/browserReader.test.js@@ -0,0 +1,98 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const navigateToUrlPinned = vi.fn();+const closeCdpPage = vi.fn(async () => {});+vi.mock('../../services/browserService.js', () => ({ navigateToUrlPinned, closeCdpPage }));+const { executeStackerNewsBrowserRead, readItems, readMe, readSub } = await import('./browserReader.js');++const page = (url, evalResult) => ({ id: 'page-1', url, evalResult });++describe('Stacker News browser read transport', () => {+ beforeEach(() => {+ navigateToUrlPinned.mockReset();+ closeCdpPage.mockClear();+ });++ 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' }));+ 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');+ });++ it('throws when the pinned browser is not signed in', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', 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,+ }));+ await expect(readSub('example')).resolves.toEqual({+ sub: { name: 'example', userId: '42', baseCost: 1, postsSatsFilter: 0, replyCost: 1, postTypes: ['LINK', 'DISCUSSION'], status: 'ACTIVE', nsfw: false },+ });+ 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));+ 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' }],+ }));+ await expect(readItems('example', 'page-2')).resolves.toEqual({+ 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' }],+ },+ });+ expect(navigateToUrlPinned.mock.calls[0][0]).toBe('https://stacker.news/~example/recent?cursor=page-2');+ });++ it('omits the cursor parameter on the first page', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news/~example/recent', { 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');+ });++ 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 },+ ],+ }));+ await expect(readItems('example')).resolves.toEqual({+ items: {+ cursor: null,+ items: [{ id: '7', createdAt: null, updatedAt: null, title: '', text: '', url: '', parentId: '9', user: { name: '' }, subName: '' }],+ },+ });+ });++ 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: [] }));+ await expect(readItems('example')).rejects.toThrow('left the fixed origin');+ expect(closeCdpPage).toHaveBeenCalledWith('page-1');+ });++ it('rejects a territory name or cursor the closed registry does not allow', async () => {+ await expect(readSub('../../etc/passwd')).rejects.toThrow('Invalid Stacker News territory name');+ await expect(readItems('example', 'x'.repeat(401))).rejects.toThrow('Invalid Stacker News cursor');+ expect(navigateToUrlPinned).not.toHaveBeenCalled();+ });++ it('dispatches named operations with the same envelope as the GraphQL transport', async () => {+ navigateToUrlPinned.mockResolvedValue(page('https://stacker.news', { id: '1', name: 'example_user' }));+ 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/integrations/stackerNews/client.js b/server/integrations/stackerNews/client.jsindex 9bde081289..600faa4283 100644--- a/server/integrations/stackerNews/client.js+++ b/server/integrations/stackerNews/client.js@@ -78,6 +78,10 @@ export async function executeStackerNewsOperation(name, input = {}, apiKey) {export const stackerNewsOperations = Object.freeze(Object.keys(OPERATIONS));export const stackerNewsCapabilities = Object.freeze({+ // `browserReads` is the DEFAULT read transport (see browserReader.js): SN+ // grants API keys only on request, so the key is an optional accelerator that+ // only reviewed writes require.+ browserReads: Object.freeze(['me', 'sub', 'items']),api: Object.freeze({ reads: ['me', 'sub', 'items'], reviewedWrites: ['createDiscussion', 'createComment'] }),browserHandoff: Object.freeze(['item', 'territory_settings', 'zap', 'downzap', 'boost']),unavailable: Object.freeze(['wallet_settlement', 'arbitrary_graphql', 'arbitrary_browser_script']),diff --git a/server/integrations/stackerNews/index.js b/server/integrations/stackerNews/index.jsindex 358af59b5e..aca828e179 100644--- a/server/integrations/stackerNews/index.js+++ b/server/integrations/stackerNews/index.js@@ -1 +1,2 @@export { executeStackerNewsOperation, stackerNewsOperations, stackerNewsCapabilities } from './client.js';+export { executeStackerNewsBrowserRead, readItems, readMe, readSub, stackerNewsBrowserReads } from './browserReader.js';diff --git a/server/lib/db/schema/stackerNews.js b/server/lib/db/schema/stackerNews.jsindex f3738cf0cb..b27aa867fd 100644--- a/server/lib/db/schema/stackerNews.js+++ b/server/lib/db/schema/stackerNews.js@@ -14,6 +14,7 @@ export const stackerNewsDdl = [vision_model TEXT NOT NULL DEFAULT '',rules JSONB NOT NULL DEFAULT '{}'::jsonb,policy_version TEXT NOT NULL DEFAULT 'v1',+ read_transport TEXT NOT NULL DEFAULT 'browser' CHECK (read_transport IN ('browser','api')),last_sync_at TIMESTAMPTZ,last_error TEXT NOT NULL DEFAULT '',created_at TIMESTAMPTZ DEFAULT NOW(),@@ -26,6 +27,10 @@ export const stackerNewsDdl = [`ALTER TABLE stacker_news_accounts ADD COLUMN IF NOT EXISTS policy_version TEXT NOT NULL DEFAULT 'v1'`,`ALTER TABLE stacker_news_accounts ADD COLUMN IF NOT EXISTS last_sync_at TIMESTAMPTZ`,`ALTER TABLE stacker_news_accounts ADD COLUMN IF NOT EXISTS last_error TEXT NOT NULL DEFAULT ''`,+ // Reads default to the signed-in pinned browser: Stacker News grants API keys+ // only on request, so a key-gated read path leaves a fresh install unable to+ // sync at all. Existing installs pick this up with no manual step.+ `ALTER TABLE stacker_news_accounts ADD COLUMN IF NOT EXISTS read_transport TEXT NOT NULL DEFAULT 'browser' CHECK (read_transport IN ('browser','api'))`,`CREATE TABLE IF NOT EXISTS stacker_news_credentials (account_id UUID PRIMARY KEY REFERENCES stacker_news_accounts (id) ON DELETE CASCADE,api_key_enc TEXT NOT NULL,diff --git a/server/routes/stackerNews.js b/server/routes/stackerNews.jsindex 6da1a690bc..6cedb55857 100644--- a/server/routes/stackerNews.js+++ b/server/routes/stackerNews.js@@ -25,6 +25,7 @@ const accountSchema = z.object({label: z.string().trim().min(1).max(120),username: z.string().trim().min(1).max(80).regex(/^[a-zA-Z0-9_-]+$/, 'must be a Stacker News username'),apiKey: z.string().trim().min(1).max(400).optional(),+ readTransport: z.enum(['browser', 'api']).optional(),enabled: z.boolean().optional(),monitoringEnabled: z.boolean().optional(),monitoringIntervalMinutes: z.number().int().min(5).max(1_440).optional(),@@ -70,6 +71,10 @@ const actionSchema = z.discriminatedUnion('kind', [ctx.addIssue({ code: 'custom', message: 'territory settings destination requires territoryId' });}});+// Optional override so "Check API identity" can test the stored key even while+// the account reads through the browser; omitted, it uses the account's own+// configured read transport.+const verifySchema = z.object({ transport: z.enum(['browser', 'api']).optional() }).strict();const reviewSchema = z.object({ state: z.enum(['approved', 'rejected']), reviewNote: z.string().max(2_000).optional() }).strict();const feedbackSchema = z.object({ feedback: z.string().trim().min(1).max(4_000) }).strict();@@ -115,7 +120,7 @@ router.delete('/accounts/:id', asyncHandler(async (req, res) => {router.post('/accounts/:id/verify', asyncHandler(async (req, res) => {requireId(req.params.id, 'account ID');- const status = await stackerNews.verifyConnection(req.params.id);+ const status = await stackerNews.verifyConnection(req.params.id, validateRequest(verifySchema, req.body || {}));if (!status) throw new ServerError('Stacker News account not found', { status: 404 });res.json(status);}));diff --git a/server/routes/stackerNews.test.js b/server/routes/stackerNews.test.jsindex 37adfa95f3..7780658f1d 100644--- a/server/routes/stackerNews.test.js+++ b/server/routes/stackerNews.test.js@@ -13,7 +13,8 @@ vi.mock('../services/stackerNews.js', () => ({createAction: vi.fn(),executeApprovedAction: vi.fn(),listAccounts: vi.fn(async () => []),- stackerNewsCapabilities: { api: { reads: ['me'] } },+ verifyConnection: vi.fn(async () => ({ configured: true, connected: true, transport: 'browser', username: 'example_steward' })),+ stackerNewsCapabilities: { browserReads: ['me'], api: { reads: ['me'] } },}));import * as stackerNews from '../services/stackerNews.js';@@ -68,4 +69,34 @@ describe('Stacker News routes', () => {expect(response.status).toBe(200);expect(stackerNews.executeApprovedAction).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000010');});++ it('accepts a read transport on create and rejects one outside the two named transports', async () => {+ const created = await request(app).post('/api/stacker-news/accounts').send({+ label: 'Example steward',+ username: 'example_steward',+ readTransport: 'browser',+ });+ expect(created.status).toBe(201);+ expect(stackerNews.createAccount).toHaveBeenCalledWith(expect.objectContaining({ readTransport: 'browser' }));++ const rejected = await request(app).post('/api/stacker-news/accounts').send({+ label: 'Example steward',+ username: 'example_steward',+ readTransport: 'graphql',+ });+ expect(rejected.status).toBe(400);+ });++ it('verifies through the account transport by default and through an explicit override when asked', async () => {+ const id = '00000000-0000-4000-8000-000000000001';+ const fallback = await request(app).post(`/api/stacker-news/accounts/${id}/verify`).send({});+ expect(fallback.status).toBe(200);+ expect(stackerNews.verifyConnection).toHaveBeenCalledWith(id, {});++ await request(app).post(`/api/stacker-news/accounts/${id}/verify`).send({ transport: 'api' });+ expect(stackerNews.verifyConnection).toHaveBeenCalledWith(id, { transport: 'api' });++ const rejected = await request(app).post(`/api/stacker-news/accounts/${id}/verify`).send({ transport: 'telepathy' });+ expect(rejected.status).toBe(400);+ });});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 52cf8dbee9..3d7f8d7791 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1285,6 +1285,7 @@ CREATE TABLE IF NOT EXISTS stacker_news_accounts (vision_model TEXT NOT NULL DEFAULT '',rules JSONB NOT NULL DEFAULT '{}'::jsonb,policy_version TEXT NOT NULL DEFAULT 'v1',+ read_transport TEXT NOT NULL DEFAULT 'browser' CHECK (read_transport IN ('browser','api')),last_sync_at TIMESTAMPTZ,last_error TEXT NOT NULL DEFAULT '',created_at TIMESTAMPTZ DEFAULT NOW(),diff --git a/server/services/browserService.js b/server/services/browserService.jsindex e737c715aa..bbe25467a9 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -422,8 +422,11 @@ const PIN_SETUP_ID_BASE = 10;// Close a CDP tab by target id (best-effort). Used to fail closed after an// SSRF-pin refusal so a tab that connected to a disallowed address is torn down-// rather than left open for the DOM reader.-async function closeCdpPage(id) {+// rather than left open for the DOM reader. Also exported for read-only callers+// (e.g. the Stacker News browser read transport) that scrape one page and must+// not leave a tab behind per sync page — unlike a handoff, whose tab is the+// deliverable.+export async function closeCdpPage(id) {if (!id) return;await cdpRequest(`/json/close/${id}`, { timeout: HEALTH_TIMEOUT_MS }).catch(() => {});}diff --git a/server/services/stackerNews.js b/server/services/stackerNews.jsindex bc874a2dc2..926892e381 100644--- a/server/services/stackerNews.js+++ b/server/services/stackerNews.js@@ -1,7 +1,7 @@import { createHash, randomUUID } from 'crypto';import { query, withTransaction } from '../lib/db.js';import { decryptValue, encryptValue, ensureVaultKey } from '../lib/vaultCrypto.js';-import { executeStackerNewsOperation, stackerNewsCapabilities } from '../integrations/stackerNews/index.js';+import { executeStackerNewsBrowserRead, executeStackerNewsOperation, stackerNewsCapabilities } from '../integrations/stackerNews/index.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { fetchAndNormalizeStackerNewsImage, hashRemoteMediaUrl } from './stackerNewsMedia.js';import { getStackerNewsBrowserIdentity, openStackerNewsHandoff } from './stackerNewsBrowser.js';@@ -17,6 +17,8 @@ import {} from './stackerNewsPolicy.js';const ACTION_KINDS = new Set(['draft_post', 'draft_comment', 'publish_post', 'publish_comment', 'open_browser', 'territory_setting']);+const READ_TRANSPORTS = new Set(['browser', 'api']);+const DEFAULT_READ_TRANSPORT = 'browser';const ACTION_STATES = new Set(['draft', 'pending_review', 'approved', 'executing', 'completed', 'failed', 'rejected']);const INJECTION_PATTERNS = [/ignore (?:all |any |the )?(?:previous|prior|system) instructions/i,@@ -42,6 +44,11 @@ const normalizedText = (value) => {const analysisText = (value) => normalizedText(value).slice(0, MAX_ANALYSIS_CHARS);const markdownImages = (body = '') => [...body.matchAll(/!\[[^\]]*\]\((https?:\/\/[^\s)]+)(?:\s+"[^"]*")?\)/gi)].map((match) => match[1]).slice(0, 12);+// Stacker News grants API keys only on request, so reads default to the+// signed-in pinned browser and the key stays an optional accelerator that only+// reviewed writes require. An account opts into `'api'` explicitly.+const normalizeReadTransport = (value) => READ_TRANSPORTS.has(value) ? value : DEFAULT_READ_TRANSPORT;+const accountView = (row) => ({id: row.id,label: row.label,@@ -54,6 +61,7 @@ const accountView = (row) => ({visionModel: row.vision_model || '',rules: row.rules || {},policyVersion: row.policy_version || POLICY_VERSION,+ readTransport: normalizeReadTransport(row.read_transport),apiKeyConfigured: Boolean(row.api_key_configured),lastSyncAt: row.last_sync_at,lastError: row.last_error || '',@@ -156,14 +164,15 @@ async function saveCredential(client, accountId, apiKey) {export async function createAccount({label, username, apiKey, enabled = true, monitoringEnabled = false,monitoringIntervalMinutes = 30, analysisEnabled = false, textModel = '', visionModel = '', rules = {},+ readTransport = DEFAULT_READ_TRANSPORT,}) {const id = randomUUID();await withTransaction(async (client) => {await client.query(`INSERT INTO stacker_news_accounts- (id,label,username,enabled,monitoring_enabled,monitoring_interval_minutes,analysis_enabled,text_model,vision_model,rules,policy_version)- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,- [id, label, username.toLowerCase(), enabled, monitoringEnabled, monitoringIntervalMinutes, analysisEnabled, textModel, visionModel, normalizeStackerNewsRules(rules), POLICY_VERSION],+ (id,label,username,enabled,monitoring_enabled,monitoring_interval_minutes,analysis_enabled,text_model,vision_model,rules,policy_version,read_transport)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,+ [id, label, username.toLowerCase(), enabled, monitoringEnabled, monitoringIntervalMinutes, analysisEnabled, textModel, visionModel, normalizeStackerNewsRules(rules), POLICY_VERSION, normalizeReadTransport(readTransport)],);if (apiKey) await saveCredential(client, id, apiKey);});@@ -177,12 +186,13 @@ export async function updateAccount(id, updates) {await withTransaction(async (client) => {await client.query(`UPDATE stacker_news_accounts SET label=$2,username=$3,enabled=$4,monitoring_enabled=$5,- monitoring_interval_minutes=$6,analysis_enabled=$7,text_model=$8,vision_model=$9,rules=$10,policy_version=$11,updated_at=NOW()+ monitoring_interval_minutes=$6,analysis_enabled=$7,text_model=$8,vision_model=$9,rules=$10,policy_version=$11,read_transport=$12,updated_at=NOW()WHERE id=$1`,[id, updates.label ?? existing.label, (updates.username ?? existing.username).toLowerCase(), updates.enabled ?? existing.enabled,updates.monitoringEnabled ?? existing.monitoring_enabled, updates.monitoringIntervalMinutes ?? existing.monitoring_interval_minutes,updates.analysisEnabled ?? existing.analysis_enabled, updates.textModel ?? existing.text_model, updates.visionModel ?? existing.vision_model,- updates.rules === undefined ? existing.rules : normalizeStackerNewsRules(updates.rules), POLICY_VERSION],+ updates.rules === undefined ? existing.rules : normalizeStackerNewsRules(updates.rules), POLICY_VERSION,+ normalizeReadTransport(updates.readTransport ?? existing.read_transport)],);if (updates.apiKey !== undefined) await saveCredential(client, id, updates.apiKey);});@@ -232,13 +242,24 @@ export async function deleteTerritory(id) {return result.rows[0]?.account_id || null;}-export async function verifyConnection(accountId) {+// Binds one of the two read transports to a `read(name, input)` with the same+// operation names and envelope, so every caller below stays transport-agnostic.+// `read` is null only for the API transport with no stored key — the caller+// decides whether that is a hard failure (sync) or a reportable state (verify).+async function openReadTransport(accountRow, requested) {+ const transport = READ_TRANSPORTS.has(requested) ? requested : normalizeReadTransport(accountRow.read_transport);+ if (transport !== 'api') return { transport, read: executeStackerNewsBrowserRead };+ const apiKey = await getCredential(accountRow.id);+ return { transport, read: apiKey ? (name, input) => executeStackerNewsOperation(name, input, apiKey) : null };+}++export async function verifyConnection(accountId, { transport: requested } = {}) {const account = await getAccountRow(accountId);if (!account) return null;- const apiKey = await getCredential(accountId);- if (!apiKey) return { configured: false, connected: false };- const data = await executeStackerNewsOperation('me', {}, apiKey);- return { configured: true, connected: true, username: data?.me?.name || null, matchesConfigured: data?.me?.name?.toLowerCase() === account.username.toLowerCase() };+ const { transport, read } = await openReadTransport(account, requested);+ if (!read) return { configured: false, connected: false, transport };+ const username = (await read('me', {}))?.me?.name || null;+ return { configured: true, connected: true, transport, username, matchesConfigured: username?.toLowerCase() === account.username.toLowerCase() };}export async function getBrowserIdentity(accountId) {@@ -387,16 +408,18 @@ async function syncAccountUnlocked(accountId, { force = false } = {}) {const territories = await listTerritories(accountId);const hasEffectiveMonitoring = territories.some((territory) => territory.monitoringEnabled ?? account.monitoring_enabled);if (!force && !hasEffectiveMonitoring) return { skipped: true, reason: 'monitoring_disabled', account: accountView({ ...account, api_key_configured: false }) };- const apiKey = await getCredential(accountId);- if (!apiKey) throw new Error('Stacker News API key is not configured');- const me = (await executeStackerNewsOperation('me', {}, apiKey))?.me;- if (!me?.name || me.name.toLowerCase() !== account.username.toLowerCase()) throw new Error(`API key identity @${me?.name || 'unknown'} does not match configured account`);+ const { transport, read } = await openReadTransport(account);+ if (!read) throw new Error('Stacker News API key is not configured');+ const me = (await read('me', {}))?.me;+ if (!me?.name || me.name.toLowerCase() !== account.username.toLowerCase()) {+ throw new Error(`${transport === 'api' ? 'API key' : 'Pinned browser'} identity @${me?.name || 'unknown'} does not match configured account`);+ }let ingested = 0;let analyzed = 0;for (const territory of territories) {const monitored = territory.monitoringEnabled ?? account.monitoring_enabled;if (!force && !monitored) continue;- const remote = (await executeStackerNewsOperation('sub', { name: territory.slug }, apiKey))?.sub;+ const remote = (await read('sub', { name: territory.slug }))?.sub;const ownershipVerified = Boolean(remote && String(remote.userId) === String(me.id));await query('UPDATE stacker_news_territories SET remote_settings=$2,remote_refreshed_at=NOW(),updated_at=NOW() WHERE id=$1',@@ -405,7 +428,7 @@ async function syncAccountUnlocked(accountId, { force = false } = {}) {let cursor = null;const seenCursors = new Set();for (let pageNumber = 0; pageNumber < 5; pageNumber += 1) {- const page = (await executeStackerNewsOperation('items', { sub: territory.slug, cursor, limit: 30 }, apiKey))?.items;+ const page = (await read('items', { sub: territory.slug, cursor, limit: 30 }))?.items;for (const remoteItem of page?.items || []) {const nextHash = stableHash(normalizedText({ title: remoteItem.title || '', body: remoteItem.text || '' }));const previous = await query('SELECT content_hash FROM stacker_news_items WHERE account_id=$1 AND remote_id=$2', [accountId, String(remoteItem.id)]);@@ -436,7 +459,7 @@ async function syncAccountUnlocked(accountId, { force = false } = {}) {}}await query("UPDATE stacker_news_accounts SET last_sync_at=NOW(),last_error='',updated_at=NOW() WHERE id=$1", [accountId]);- return { skipped: false, username: me.name, territories: territories.length, ingested, analyzed };+ return { skipped: false, transport, username: me.name, territories: territories.length, ingested, analyzed };}export async function syncAccount(accountId, options = {}) {diff --git a/server/services/stackerNewsBrowser.js b/server/services/stackerNewsBrowser.jsindex 1e1277430a..79c2973da8 100644--- a/server/services/stackerNewsBrowser.js+++ b/server/services/stackerNewsBrowser.js@@ -22,7 +22,10 @@ const fixedUrl = (kind, value) => {throw new Error('Unsupported Stacker News browser destination');};-const verifyFinalOrigin = (url) => {+// Exported so every Stacker News browser path (handoffs AND the read transport+// in integrations/stackerNews/browserReader.js) fails closed on the same check —+// a redirect that leaves the fixed origin must never be treated as SN data.+export const verifyFinalOrigin = (url) => {const parsed = new URL(url);if (parsed.origin !== ORIGIN) throw new Error('Stacker News browser navigation left the fixed origin');};diff --git a/server/services/stackerNewsSync.test.js b/server/services/stackerNewsSync.test.jsindex fc81d23f84..070428904a 100644--- a/server/services/stackerNewsSync.test.js+++ b/server/services/stackerNewsSync.test.js@@ -2,33 +2,47 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const accountId = '00000000-0000-4000-8000-000000000001';const territoryId = '00000000-0000-4000-8000-000000000002';+let accountRow = {};+let credentialRows = [];const query = vi.fn(async (sql) => {- if (sql.startsWith('SELECT * FROM stacker_news_accounts')) return { rows: [{ id: accountId, label: 'Example', username: 'example_user', enabled: true, monitoring_enabled: false, monitoring_interval_minutes: 30, analysis_enabled: false, text_model: '', vision_model: '', rules: {}, policy_version: 'v1' }] };- if (sql.startsWith('SELECT api_key_enc')) return { rows: [{ api_key_enc: 'ciphertext' }] };+ if (sql.startsWith('SELECT * FROM stacker_news_accounts')) return { rows: [accountRow] };+ if (sql.startsWith('SELECT api_key_enc')) return { rows: credentialRows };if (sql.startsWith('SELECT * FROM stacker_news_territories')) return { rows: [{ id: territoryId, account_id: accountId, slug: 'art', label: 'Art', is_owned: true, monitoring_enabled: true, inherit_account_rules: true, rules: {}, remote_settings: {} }] };if (sql.startsWith('SELECT content_hash')) return { rows: [] };if (sql.includes('INSERT INTO stacker_news_items')) return { rows: [{ id: '00000000-0000-4000-8000-000000000003', account_id: accountId, territory_id: territoryId, remote_id: '42', kind: 'post', author_name: 'artist', title: 'Example work', body: 'A post', source_url: 'https://stacker.news/items/42', image_urls: [], content_hash: 'hash', received_at: new Date() }] };return { rows: [], rowCount: 1 };});+const itemsPage = (cursor) => cursor+ ? { items: { cursor: null, items: [] } }+ : { items: { cursor: 'page-2', items: [{ id: '42', title: 'Example work', text: 'A post', user: { name: 'artist' } }] } };const executeStackerNewsOperation = vi.fn(async (name, input) => {if (name === 'me') return { me: { id: 'owner-1', name: 'example_user' } };if (name === 'sub') return { sub: { name: 'art', userId: 'owner-1' } };- if (name === 'items' && !input.cursor) return { items: { cursor: 'page-2', items: [{ id: '42', title: 'Example work', text: 'A post', user: { name: 'artist' } }] } };- return { items: { cursor: null, items: [] } };+ return itemsPage(input.cursor);+});+const executeStackerNewsBrowserRead = vi.fn(async (name, input = {}) => {+ if (name === 'me') return { me: { id: 'owner-1', name: 'example_user' } };+ if (name === 'sub') return { sub: { name: 'art', userId: 'owner-1' } };+ return itemsPage(input.cursor);});vi.mock('../lib/db.js', () => ({ query, withTransaction: vi.fn() }));vi.mock('../lib/vaultCrypto.js', () => ({ decryptValue: () => 'api-key', encryptValue: vi.fn(), ensureVaultKey: vi.fn() }));-vi.mock('../integrations/stackerNews/index.js', () => ({ executeStackerNewsOperation, stackerNewsCapabilities: {} }));-const { syncAccount } = await import('./stackerNews.js');+vi.mock('../integrations/stackerNews/index.js', () => ({ executeStackerNewsOperation, executeStackerNewsBrowserRead, stackerNewsCapabilities: {} }));+const { syncAccount, verifyConnection } = await import('./stackerNews.js');++const baseAccount = { id: accountId, label: 'Example', username: 'example_user', enabled: true, monitoring_enabled: false, monitoring_interval_minutes: 30, analysis_enabled: false, text_model: '', vision_model: '', rules: {}, policy_version: 'v1' };describe('Stacker News sync', () => {beforeEach(() => {query.mockClear();executeStackerNewsOperation.mockClear();+ executeStackerNewsBrowserRead.mockClear();+ accountRow = { ...baseAccount, read_transport: 'api' };+ credentialRows = [{ api_key_enc: 'ciphertext' }];});it('paginates named reads, verifies ownership, and ingests without analyzing when analysis is off', async () => {- await expect(syncAccount(accountId, { force: true })).resolves.toMatchObject({ ingested: 1, analyzed: 0 });+ await expect(syncAccount(accountId, { force: true })).resolves.toMatchObject({ ingested: 1, analyzed: 0, transport: 'api' });const itemCalls = executeStackerNewsOperation.mock.calls.filter(([name]) => name === 'items');expect(itemCalls).toHaveLength(2);expect(itemCalls[0][1]).toMatchObject({ sub: 'art', cursor: null });@@ -40,4 +54,29 @@ describe('Stacker News sync', () => {await expect(syncAccount(accountId)).resolves.toMatchObject({ skipped: false, ingested: 1 });expect(executeStackerNewsOperation).toHaveBeenCalledWith('sub', expect.objectContaining({ name: 'art' }), 'api-key');});++ // Stacker News grants API keys on request only, so the default install has no+ // key at all — reads must still work through the signed-in pinned browser.+ it('syncs with no API key stored by reading through the pinned browser', async () => {+ accountRow = { ...baseAccount };+ credentialRows = [];+ await expect(syncAccount(accountId, { force: true })).resolves.toMatchObject({ ingested: 1, transport: 'browser' });+ expect(executeStackerNewsOperation).not.toHaveBeenCalled();+ const itemCalls = executeStackerNewsBrowserRead.mock.calls.filter(([name]) => name === 'items');+ expect(itemCalls.map(([, input]) => input.cursor)).toEqual([null, 'page-2']);+ });++ it('still refuses an API-transport account with no key', async () => {+ credentialRows = [];+ await expect(syncAccount(accountId, { force: true })).rejects.toThrow('Stacker News API key is not configured');+ });++ it('resolves the signed-in username with no key, and can be forced onto the API', async () => {+ accountRow = { ...baseAccount };+ credentialRows = [];+ await expect(verifyConnection(accountId)).resolves.toMatchObject({ configured: true, connected: true, transport: 'browser', username: 'example_user', matchesConfigured: true });+ await expect(verifyConnection(accountId, { transport: 'api' })).resolves.toMatchObject({ configured: false, connected: false, transport: 'api' });+ credentialRows = [{ api_key_enc: 'ciphertext' }];+ await expect(verifyConnection(accountId, { transport: 'api' })).resolves.toMatchObject({ configured: true, transport: 'api', username: 'example_user' });+ });});