Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): send the sign-in's utm_* and rid to /api/auth/exchange

0xken159092819e2108
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d15f02d89..3d2cc3b09 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -64,7 +64,7 @@ import { serviceCommand, serviceCommandDeps } from './lib/serviceCommand.js'
import { ensureTmuxOnPath } from './lib/tmuxOnPath.js'
import { flashCommand } from './lib/flash.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
-import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'
+import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, type LoginCallbackParams } from './lib/loginCallback.js'
import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, knownSsoClientId, newSignInEpoch, readAuthSession, signInOf, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { handOffToGrid } from './lib/gridHandoff.js'
import { qrSignIn } from './lib/qrSignIn.js'
@@ -1118,7 +1118,7 @@ async function browserSignIn(
// redirect never arrives here. It still lands on a URL carrying `code`/`state` (the page just fails
// to load); let them paste that URL back in instead of hanging until the 5-minute timeout.
const manual = !json && process.stdin.isTTY ? promptForCallbackUrl(redirectUri) : null
- let callbackResult: { code: string; state: string }
+ let callbackResult: LoginCallbackParams
try {
callbackResult = await awaitLoginCallback({ server: callback, redirectUri, manual: manual?.promise ?? null, timeoutMs: 5 * 60_000, entryPoint })
} catch (err) {
@@ -1133,8 +1133,11 @@ async function browserSignIn(
let exchanged: { token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag'; clientId?: string }
try {
exchanged = await postJson<typeof exchanged>('/api/auth/exchange', {
- ...callbackResult,
+ code: callbackResult.code,
+ state: callbackResult.state,
tx: start.tx,
+ // The utm_* and rid auth.autonomous.ai carried back: how the account came (PR #785).
+ ...(callbackResult.attribution ? { attribution: callbackResult.attribution } : {}),
})
if (!exchanged.token) throw new Error('SSO exchange returned no access token')
} catch (err) {
@@ -1296,12 +1299,12 @@ async function gridEnvCommand(grid: string | undefined): Promise<void> {
* on the way out either way.
*/
function promptForCallbackUrl(redirectUri: string): {
- promise: Promise<{ code: string; state: string }>
+ promise: Promise<LoginCallbackParams>
cancel: () => void
} {
const rl = createInterface({ input: process.stdin, output: process.stdout })
let settled = false
- const promise = new Promise<{ code: string; state: string }>((resolve, reject) => {
+ const promise = new Promise<LoginCallbackParams>((resolve, reject) => {
const ask = (): void => {
rl.question(
'\n If your browser could not reach back to this machine (SSH/remote), paste the URL it landed on\n' +
@@ -1310,14 +1313,14 @@ function promptForCallbackUrl(redirectUri: string): {
if (settled) return
const trimmed = answer.trim()
if (!trimmed) { ask(); return }
- const { code, state, error } = extractCallbackParams(trimmed, redirectUri)
+ const { code, state, error, attribution } = extractCallbackParams(trimmed, redirectUri)
if (error) { reject(new Error(`SSO login failed: ${error}`)); return }
if (!code || !state) {
console.log(' No login code found in that — paste the full callback URL or its code=...&state=... part.')
ask()
return
}
- resolve({ code, state })
+ resolve({ code, state, ...(attribution ? { attribution } : {}) })
},
)
}
diff --git a/cli/src/lib/loginCallback.spec.ts b/cli/src/lib/loginCallback.spec.ts
index baf5ce437..4dcbc021d 100644
--- a/cli/src/lib/loginCallback.spec.ts
+++ b/cli/src/lib/loginCallback.spec.ts
@@ -1,6 +1,6 @@
import { createServer, type Server } from 'http'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './loginCallback.js'
+import { awaitLoginCallback, callbackAttribution, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './loginCallback.js'
const REDIRECT = 'http://127.0.0.1:4321/callback'
@@ -90,6 +90,26 @@ describe('awaitLoginCallback', () => {
expect(cliPage).toContain('return to the terminal')
})
+ it('brings back where the sign-in came from, as auth.autonomous.ai appended it to the redirect', async () => {
+ // The desktop app signs in through this loopback. Before, only code/state were read, so a person who
+ // downloaded the app from a tagged autonomous.ai/harness-app link was never attributed (prod E2E, 2026-10-06).
+ const { server, redirectUri } = await listening()
+ const pending = awaitLoginCallback({ server, redirectUri, manual: null, timeoutMs: 60_000 })
+ await fetch(`${redirectUri}?code=c&iss=https%3A%2F%2Fauth.autonomous.ai&rid=r1&state=s&utm_campaign=launch&utm_content=&utm_source=app&utm_term=`)
+ await expect(pending).resolves.toEqual({
+ code: 'c',
+ state: 's',
+ attribution: { rid: 'r1', utm_campaign: 'launch', utm_source: 'app' },
+ })
+ })
+
+ it('carries no attribution for an untagged sign-in', async () => {
+ const { server, redirectUri } = await listening()
+ const pending = awaitLoginCallback({ server, redirectUri, manual: null, timeoutMs: 60_000 })
+ await fetch(`${redirectUri}?code=c&state=s`)
+ expect(await pending).not.toHaveProperty('attribution')
+ })
+
it('rejects on an error redirect, with a 400 for the browser', async () => {
const { server, redirectUri } = await listening()
// The rejection lands before the browser's response is read, so the expectation is attached first.
@@ -126,4 +146,24 @@ describe('extractCallbackParams', () => {
// The raw query-string fallback reads what it can; without a `code` the prompt just asks again.
expect(extractCallbackParams('http://ex ample/?code=a&state=b', REDIRECT)).toMatchObject({ code: null })
})
+
+ it('reads the tags from a pasted URL or query string too', () => {
+ // Over SSH the person pastes the URL the browser landed on; it carries the same tags.
+ expect(extractCallbackParams(`${REDIRECT}?code=a&state=b&rid=r1&utm_medium=email`, REDIRECT))
+ .toEqual({ code: 'a', state: 'b', error: null, attribution: { rid: 'r1', utm_medium: 'email' } })
+ expect(extractCallbackParams('code=a&state=b&utm_source=app', REDIRECT))
+ .toEqual({ code: 'a', state: 'b', error: null, attribution: { utm_source: 'app' } })
+ })
+})
+
+describe('callbackAttribution', () => {
+ it('keeps only the utm keys and rid, trimmed', () => {
+ expect(callbackAttribution(new URLSearchParams('utm_source=%20app%20&role=admin&iss=x&rid=r1')))
+ .toEqual({ utm_source: 'app', rid: 'r1' })
+ })
+
+ it('is absent rather than empty when nothing usable was sent', () => {
+ expect(callbackAttribution(new URLSearchParams('code=a&state=b'))).toBeUndefined()
+ expect(callbackAttribution(new URLSearchParams('utm_term=&utm_content=%20%20'))).toBeUndefined()
+ })
})
diff --git a/cli/src/lib/loginCallback.ts b/cli/src/lib/loginCallback.ts
index 974179093..58bcdc904 100644
--- a/cli/src/lib/loginCallback.ts
+++ b/cli/src/lib/loginCallback.ts
@@ -1,7 +1,37 @@
import type { IncomingMessage, Server, ServerResponse } from 'http'
import { renderLoginSuccessHtml } from './loginPage.js'
-export interface LoginCallbackParams { code: string; state: string }
+/** The `utm_*` and `rid` of a sign-in, under their URL keys. See callbackAttribution. */
+export type CallbackAttribution = Record<string, string>
+
+export interface LoginCallbackParams {
+ code: string
+ state: string
+ /** Where the sign-in came from, for `/api/auth/exchange` to record on the account. */
+ attribution?: CallbackAttribution
+}
+
+/**
+ * The keys auth.autonomous.ai carries back onto the callback: the `utm_*` tags and Autonomous's referral
+ * id `rid`. The marketing site (autonomous.ai/harness-app, where the desktop app is downloaded) leaves
+ * them in `.autonomous.ai` cookies, and the sign-in page appends them to our redirect_uri. Same keys as
+ * the web client (desktop/lib/viewer/sign_in_attribution.dart) and the backend (lib/signInAttribution.ts).
+ */
+const ATTRIBUTION_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'rid'] as const
+
+/**
+ * The [ATTRIBUTION_KEYS] of a callback, under their URL keys, or nothing when it carries none. Empty
+ * values are dropped: the site sets `utm_term=` and `utm_content=` even when the link had neither.
+ * The backend filters and caps these again — the code exchange is reachable by anyone holding a code.
+ */
+export function callbackAttribution(params: URLSearchParams): CallbackAttribution | undefined {
+ const attribution: CallbackAttribution = {}
+ for (const key of ATTRIBUTION_KEYS) {
+ const value = params.get(key)?.trim()
+ if (value) attribution[key] = value
+ }
+ return Object.keys(attribution).length ? attribution : undefined
+}
/** The exact message `harness login --json` maps to `code: 'TIMEOUT'` — keep the string stable. */
export const LOGIN_TIMEOUT_MESSAGE = 'SSO login timed out'
@@ -20,12 +50,17 @@ export function extractCallbackParams(input: string, redirectUri: string): {
code: string | null
state: string | null
error: string | null
+ attribution?: CallbackAttribution
} {
- const read = (params: URLSearchParams) => ({
- code: params.get('code'),
- state: params.get('state'),
- error: params.get('error'),
- })
+ const read = (params: URLSearchParams) => {
+ const attribution = callbackAttribution(params)
+ return {
+ code: params.get('code'),
+ state: params.get('state'),
+ error: params.get('error'),
+ ...(attribution ? { attribution } : {}),
+ }
+ }
try {
const viaUrl = read(new URL(input, redirectUri).searchParams)
if (viaUrl.code || viaUrl.state || viaUrl.error) return viaUrl
@@ -62,7 +97,10 @@ export function awaitLoginCallback(opts: {
? '<h1>Harness login failed</h1><p>You can close this window.</p>'
: renderLoginSuccessHtml(entryPoint))
if (error) reject(new Error(`SSO login failed: ${error}`))
- else if (code && state) resolve({ code, state })
+ else if (code && state) {
+ const attribution = callbackAttribution(url.searchParams)
+ resolve({ code, state, ...(attribution ? { attribution } : {}) })
+ }
}
// Hoisted so the handler above can settle the promise, and be removed once it has: the server
// outlives this race (it is closed by the caller), and a late redirect must not touch a settled login.