Skip to content

The agent that grows with you

fix(desktop): prove the sign-in wall from curl's arrival URL and title too

teknium13d0bdce9f928
diff --git a/apps/desktop/electron/link-title-wall.test.ts b/apps/desktop/electron/link-title-wall.test.ts
index fa191c310af..abfd3217567 100644
--- a/apps/desktop/electron/link-title-wall.test.ts
+++ b/apps/desktop/electron/link-title-wall.test.ts
@@ -2,10 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import { isAuthWallBody, needsRendererFallback, resolveLinkTitle } from './link-title-wall'
-
-const SIGNIN_IDENTIFIER_BODY =
- '<html><head><title>Google Drive: Sign-in</title></head><body><input id="identifierId"></body></html>'
+import { isAuthWall, resolveLinkTitle } from './link-title-wall'
// A published Doc answers the cookieless curl tier with its own <title>, so these
// links must stay fetchable — the wall is proven at fetch time, not from the host.
@@ -28,25 +25,14 @@ test('a proven sign-in wall never escalates to the hidden renderer', async () =>
assert.equal(title, '')
assert.equal(rendererCalls, 0)
-})
-
-test('a title-less page on a host that can only answer with a wall skips the renderer', async () => {
- // The measured domain-restricted Apps Script shape: a 2 KB body carrying none
- // of the markers the identifier page does, so the host is what holds.
- let rendererCalls = 0
-
- const title = await resolveLinkTitle({
- curl: tier1({ authWall: false, title: '' }),
- renderer: async () => {
- rendererCalls += 1
-
- return ''
- },
- url: 'https://script.google.com/a/example.edu/macros/s/abc/exec'
- })
- assert.equal(title, '')
- assert.equal(rendererCalls, 0)
+ // The three measured shapes of the wall are all proven from the curl tier:
+ // arrival URL (Apps Script → www.google.com/a/<domain>/ServiceLogin), sign-in
+ // title (Drive → accounts.google.com), and markup (a Doc that stays on its host).
+ assert.equal(isAuthWall({ body: '', effectiveUrl: 'https://www.google.com/a/x.org/ServiceLogin?c=1', title: '' }), true)
+ assert.equal(isAuthWall({ body: '', effectiveUrl: 'https://accounts.google.com/v3/signin/identifier', title: 'Google Drive: Sign-in' }), true)
+ assert.equal(isAuthWall({ body: '<a href="https://accounts.google.com/ServiceLogin">', effectiveUrl: 'https://docs.google.com/document/d/1/edit', title: '' }), true)
+ assert.equal(isAuthWall({ body: '<title>Q3 plan</title>', effectiveUrl: 'https://docs.google.com/document/d/1/pub', title: 'Q3 plan' }), false)
})
test('an ordinary title-less page still escalates to the hidden renderer', async () => {
@@ -67,70 +53,3 @@ test('an ordinary title-less page still escalates to the hidden renderer', async
assert.equal(title, 'Lab AI service — guides')
assert.equal(rendererCalls, 1)
})
-
-test('a usable tier-1 title never escalates', async () => {
- let rendererCalls = 0
-
- const title = await resolveLinkTitle({
- curl: tier1({ title: 'Which model to use' }),
- renderer: async () => {
- rendererCalls += 1
-
- return 'Something else'
- },
- url: 'https://docs.google.com/document/d/abc123/pub'
- })
-
- assert.equal(title, 'Which model to use')
- assert.equal(rendererCalls, 0)
-})
-
-test('an error/captcha title is not usable and escalates on an ordinary host', async () => {
- // usableTitle drops the captcha title, so it reads as "nothing found" — the
- // renderer tier is still allowed to try (that is its documented purpose).
- let rendererCalls = 0
-
- const title = await resolveLinkTitle({
- curl: tier1({ title: 'Just a moment...' }),
- renderer: async () => {
- rendererCalls += 1
-
- return 'Real page title'
- },
- url: 'https://example.com/cloudflare-protected'
- })
-
- assert.equal(title, 'Real page title')
- assert.equal(rendererCalls, 1)
-
- // On a wall host the same empty answer must not escalate.
- assert.equal(needsRendererFallback({ authWall: false, title: '', url: 'https://drive.google.com/x' }), false)
- assert.equal(needsRendererFallback({ authWall: false, title: '', url: 'https://example.com/x' }), true)
-})
-
-test('the sign-in wall is recognised in the body curl already returned', () => {
- assert.equal(isAuthWallBody(SIGNIN_IDENTIFIER_BODY), true)
- assert.equal(isAuthWallBody('<a href="https://accounts.google.com/ServiceLogin?continue=x">Sign in</a>'), true)
- assert.equal(isAuthWallBody('<html><head><title>Which model to use</title></head></html>'), false)
- assert.equal(isAuthWallBody(''), false)
-})
-
-test('needsRendererFallback only refuses the hosts that can only answer with a wall', () => {
- for (const url of [
- 'https://accounts.google.com/signin',
- 'https://docs.google.com/document/d/abc/edit',
- 'https://drive.google.com/drive/folders/abc',
- 'https://sheets.google.com/spreadsheets/d/abc',
- 'https://slides.google.com/presentation/d/abc',
- 'https://sites.google.com/example.edu/x/',
- 'https://script.google.com/a/example.edu/macros/s/abc/exec',
- 'https://console.cloud.google.com/apis/library/docs.googleapis.com'
- ]) {
- assert.equal(needsRendererFallback({ authWall: false, title: '', url }), false, url)
- }
-
- // A lookalike host is not a Google host, and a URL that won't parse is not a refusal.
- for (const url of ['https://example.com/docs', 'https://github.com/NousResearch/hermes-agent', 'not a url']) {
- assert.equal(needsRendererFallback({ authWall: false, title: '', url }), true, url)
- }
-})
diff --git a/apps/desktop/electron/link-title-wall.ts b/apps/desktop/electron/link-title-wall.ts
index d339fcfd4c4..136996d59a1 100644
--- a/apps/desktop/electron/link-title-wall.ts
+++ b/apps/desktop/electron/link-title-wall.ts
@@ -52,8 +52,33 @@ function hostOf(rawUrl: string): string {
}
}
-export function isAuthWallBody(body: string): boolean {
- return AUTH_WALL_BODY_RE.test(body || '')
+/** Arrival URL or title of a sign-in page — the shapes that carry no markup id. */
+const AUTH_WALL_URL_RE = /^accounts\.google\.com$|\/ServiceLogin\b|\/signin\b|\/o\/oauth2\//i
+const AUTH_WALL_TITLE_RE = /\bsign[ -]?in\b/i
+
+/**
+ * Curl's proof that the page it landed on is a sign-in wall, decided on the
+ * arrival URL → the title → the markup, in that order of reliability: an Apps
+ * Script `/a/<domain>/ServiceLogin` wall carries none of the markup ids.
+ */
+export function isAuthWall(input: { body: string; effectiveUrl: string; title: string }): boolean {
+ let arrival: URL | null = null
+
+ try {
+ arrival = input.effectiveUrl ? new URL(input.effectiveUrl) : null
+ } catch {
+ arrival = null
+ }
+
+ if (arrival && (AUTH_WALL_URL_RE.test(arrival.hostname) || AUTH_WALL_URL_RE.test(arrival.pathname))) {
+ return true
+ }
+
+ if (AUTH_WALL_TITLE_RE.test(input.title || '')) {
+ return true
+ }
+
+ return AUTH_WALL_BODY_RE.test(input.body || '')
}
/**
@@ -90,7 +115,8 @@ export async function resolveLinkTitle(input: {
url: string
}): Promise<string> {
const tier1 = await input.curl().catch(() => ({ authWall: false, title: '' }))
- const title = usableTitle((tier1.title || '').slice(0, TITLE_MAX_CHARS))
+ // A wall's own title ("Sign in - Google Accounts") is not the document's.
+ const title = tier1.authWall ? '' : usableTitle((tier1.title || '').slice(0, TITLE_MAX_CHARS))
if (!needsRendererFallback({ authWall: tier1.authWall, title, url: input.url })) {
return title
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index a68b6bf412e..ce1c54512fd 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -265,7 +265,7 @@ import { createHudSnapShortcut } from './hud-snap-shortcut'
import { buildHudWindowUrl } from './hud-url'
import { resolveHudWindowing } from './hud-windowing'
import { createIntroRevealWindowController } from './intro-reveal-window'
-import { isAuthWallBody, resolveLinkTitle } from './link-title-wall'
+import { isAuthWall, resolveLinkTitle } from './link-title-wall'
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
import { notifyLauncherWindowRevealed } from './linux-launcher-ready'
import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
@@ -3392,6 +3392,7 @@ async function checkUpdatesViaApi({ slug, branch, currentSha, updateRoot }) {
// Compare failure (rate-limited, local-only HEAD 404) keeps the honest
// "update available, count unknown" — never a fabricated number.
let compareError = null
+
const compared = await fetchGitHubApi(compareApiUrl(slug, currentSha, targetSha))
.then(parseCompare)
.catch(error => {
@@ -5999,6 +6000,23 @@ function parseHtmlTitle(html) {
return raw ? decodeHtmlEntities(raw).replace(/\s+/g, ' ').trim() : ''
}
+// `--write-out` trailer: `\n<mark><url_effective>` after the body.
+const URL_EFFECTIVE_MARK = 'hermes-url-effective:'
+const URL_EFFECTIVE_TAIL_BYTES = 4096
+
+function splitUrlEffective(stdout: string): { effectiveUrl: string; html: string } {
+ const at = stdout.lastIndexOf(`\n${URL_EFFECTIVE_MARK}`)
+
+ if (at < 0) {
+ return { effectiveUrl: '', html: stdout }
+ }
+
+ return {
+ effectiveUrl: stdout.slice(at + 1 + URL_EFFECTIVE_MARK.length).trim(),
+ html: stdout.slice(0, at)
+ }
+}
+
function fetchHtmlTitleWithCurl(rawUrl: string): Promise<{ authWall: boolean; title: string }> {
return new Promise(resolve => {
const url = String(rawUrl || '').trim()
@@ -6026,19 +6044,28 @@ function fetchHtmlTitleWithCurl(rawUrl: string): Promise<{ authWall: boolean; ti
'--header',
'Accept-Encoding: identity',
'--raw',
+ // Arrival URL after redirects, on its own line after the body: a sign-in
+ // wall is proven from where curl landed even when the page has no markup id.
+ '--write-out',
+ `\n${URL_EFFECTIVE_MARK}%{url_effective}`,
url
]
const child = spawn('curl', args, hiddenWindowsChildOptions({ stdio: ['ignore', 'pipe', 'ignore'] }))
const chunks: Buffer[] = []
+ // The last bytes of stdout, kept past the body budget so the `--write-out`
+ // arrival URL survives a body larger than TITLE_BYTE_BUDGET.
+ let tail = Buffer.alloc(0)
let bytes = 0
child.stdout.on('data', chunk => {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ tail = Buffer.concat([tail, buffer]).subarray(-URL_EFFECTIVE_TAIL_BYTES)
+
if (bytes >= TITLE_BYTE_BUDGET) {
return
}
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
const remaining = TITLE_BYTE_BUDGET - bytes
const next = buffer.length > remaining ? buffer.subarray(0, remaining) : buffer
chunks.push(next)
@@ -6051,11 +6078,18 @@ function fetchHtmlTitleWithCurl(rawUrl: string): Promise<{ authWall: boolean; ti
return resolve({ authWall: false, title: '' })
}
- const html = Buffer.concat(chunks).toString('utf8')
+ const body = Buffer.concat(chunks)
+
+ // The trailer is inside `body` unless the budget cut it off; then it is in `tail`.
+ const { effectiveUrl, html } = splitUrlEffective(
+ (bytes >= TITLE_BYTE_BUDGET ? Buffer.concat([body, tail]) : body).toString('utf8')
+ )
+
+ const title = parseHtmlTitle(html)
// A sign-in wall answers the cookieless title partition, and tier 2 must
// never load it: the wall asks the OS for a passkey.
- resolve({ authWall: isAuthWallBody(html), title: parseHtmlTitle(html) })
+ resolve({ authWall: isAuthWall({ body: html, effectiveUrl, title }), title })
})
})
}
@@ -6517,6 +6551,7 @@ async function previewFileTarget(rawTarget, baseDir) {
for (const candidate of homeRelativeAttachmentCandidates(raw, app.getPath('home'), HERMES_HOME)) {
if (fileExists(candidate)) {
resolved = candidate
+
break
}
}
@@ -10048,9 +10083,11 @@ async function buildRemoteConnection(
}
const sshConnections = new Map<string, any>()
+
const sshIsolatedKeepalives = createSshIsolatedKeepaliveRegistry({
log: chunk => sshRememberLog(chunk)
})
+
const desktopInstallationId = loadOrCreateInstallationId(DESKTOP_INSTALLATION_PATH)
// Managed SSH update lifecycle (#93042): while an update owns a registered
@@ -12336,6 +12373,7 @@ function startPoolIdleReaper() {
const retiring = entry.process
? poolRetirer.retireIdle(profile, poolIdleMs())
: stopPoolBackend(profile)
+
void retiring.catch(error => rememberLog(`Pool idle retirement failed: ${String(error)}`))
}
}
@@ -12623,6 +12661,7 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;
const startFailed = new Promise((_resolve, reject) => {
rejectStart = reject
})
+
// Exit/error can now arrive while the ownership claim is still pending.
startFailed.catch(() => {})
@@ -12658,6 +12697,7 @@ async function runPoolBackendStart(profile, entry, opts: { forceLocal?: boolean;
describeOutputTail: () => outputTail.describe(),
readyFile
})
+
portAnnouncement.catch(() => {})
await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)
assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
@@ -12740,10 +12780,12 @@ const poolStopper = createPoolStopper({
function stopPoolBackend(profile: string): Promise<void> {
const entry = backendPool.get(profile)
+
const stopping = releaseLocalBackendSlotAfterExit(
() => releaseLocalBackendSlot(entry),
() => poolStopper.stop(profile)
)
+
// Fire-and-forget callers still need diagnostics; awaiters receive the
// rejection, while physical ownership and the exit finalizer remain live.
void stopping.catch(error => {
@@ -12774,6 +12816,7 @@ const poolRetirer = createPoolRetirer({
onRetiring: broadcastPoolBackendRetiring,
log: rememberLog
})
+
localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })
async function teardownPoolBackendAndWait(profile) {
@@ -12802,6 +12845,7 @@ const backendShutdown = createBackendShutdownCoordinator(async () => {
})
const quitTeardown = createQuitTeardownCoordinator(() => app.quit())
+
const quitFinalization = createQuitFinalization({
isWindows: IS_WINDOWS,
hardExit: code => {
@@ -12913,6 +12957,7 @@ function scheduleUnexpectedPrimaryRecovery({ code = null, signal = null, error =
if (primaryExitRecovery.isCrashLooping()) {
const message =
'Hermes backend keeps crashing right after it restarts; not restarting it again. Relaunch Hermes Desktop.'
+
rememberLog(`[supervisor] ${message}`)
sendBackendExit({ code, signal, error: message })
@@ -13760,6 +13805,7 @@ function createInstanceWindow(
source && !source.isDestroyed() ? windowConnectionRoutes.get(source.webContents.id) : null,
{ connectionId: null, profile: primaryProfileKey() }
)
+
validateDesktopProfileRoute(route)
const icon = getAppIconPath()
@@ -16809,6 +16855,7 @@ async function dispatchRegistryApiRequest(
// OUT of the claim: an interactive open coalescing onto an in-flight
// passive read would otherwise inherit its "no warm backend" rejection.
const spawnPriority = spawnPriorityFrom(request?.priority)
+
const connection: any = request?.passive
? await ensureRegistryBackend(registryConnectionId, routeProfile, '', { passive: true })
: await backendDialClaims.run(backendScopeKey(registryConnectionId, routeProfile), () =>
@@ -18424,6 +18471,7 @@ function heldQuitForActiveWork(event: Electron.Event): boolean {
}
const prompt = quitPromptFor(mergeActiveWork(activeWorkByWebContents.values()), isQuittingForHandoff)
+
// A hidden aux window must never parent the quit prompt: the dialog would
// be invisible and the held quit unanswerable (#116376 §E).
const parent =