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.

feat(login): record whether a sign-in came from the terminal or the app (#197)

Dev at Autonomous63996c8ac715
diff --git a/backend/src/lib/sso.ts b/backend/src/lib/sso.ts
index 178d2dc5f..21c0d5384 100644
--- a/backend/src/lib/sso.ts
+++ b/backend/src/lib/sso.ts
@@ -126,6 +126,22 @@ export function webCallbackUri(webOrigin: string): string {
return env.SSO_REDIRECT_URI || `${webOrigin.replace(/\/$/, '')}/auth/callback`
}
+/**
+ * Where a sign-in started, as auth-service's login tracking records it (`entry_point` on
+ * `login_events`, and from there BigQuery). Ours are `cli` and `desktop`; the storefront sends
+ * keys like `sign-modal--orders_and_returns`.
+ *
+ * Narrowed to a plain key on purpose: `/api/auth/authorize-native` needs no token, this value goes
+ * into the authorize URL's query and then into a reporting column, and auth-service only truncates
+ * at 255. Anything else is dropped rather than passed on — a missing entry point reports as "none",
+ * which is honest, while a junk one is a row nobody can read.
+ */
+export function normalizeEntryPoint(raw: unknown): string | undefined {
+ if (typeof raw !== 'string') return undefined
+ const value = raw.trim().toLowerCase()
+ return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(value) ? value : undefined
+}
+
/** Where to send the browser to log in. `prompt=select_account` (env) forces the account picker so
* a user can switch accounts even when an SSO session already exists. */
export function authorizeUrl(
@@ -133,6 +149,7 @@ export function authorizeUrl(
state: string,
redirectUri: string,
autonomousEnv: AutonomousEnvironment,
+ entryPoint?: string,
): string {
const config = autonomousEnvironmentConfig(autonomousEnv)
const u = new URL('/oauth2/authorize', config.ssoIssuer)
@@ -144,6 +161,7 @@ export function authorizeUrl(
u.searchParams.set('code_challenge_method', 'S256')
u.searchParams.set('state', state)
if (env.SSO_PROMPT) u.searchParams.set('prompt', env.SSO_PROMPT)
+ if (entryPoint) u.searchParams.set('entry_point', entryPoint)
return u.toString()
}
diff --git a/backend/src/lib/ssoEntryPoint.test.ts b/backend/src/lib/ssoEntryPoint.test.ts
new file mode 100644
index 000000000..319ca98b2
--- /dev/null
+++ b/backend/src/lib/ssoEntryPoint.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import { normalizeEntryPoint } from './sso.js'
+
+/**
+ * `entry_point` is where a sign-in started. It reaches auth-service's login_events and BigQuery,
+ * and `/api/auth/authorize-native` is unauthenticated, so whatever is accepted here is what an
+ * anonymous caller can write into our analytics. auth-service itself only truncates at 255.
+ */
+describe('entry point', () => {
+ it('keeps the values this product sends', () => {
+ expect(normalizeEntryPoint('cli')).toBe('cli')
+ expect(normalizeEntryPoint('desktop')).toBe('desktop')
+ })
+
+ it('accepts the shape web sign-ins already use', () => {
+ expect(normalizeEntryPoint('sign-modal--orders_and_returns')).toBe('sign-modal--orders_and_returns')
+ })
+
+ it('trims and lowercases, so one place is not two rows in the report', () => {
+ expect(normalizeEntryPoint(' Desktop ')).toBe('desktop')
+ expect(normalizeEntryPoint('cli\n')).toBe('cli')
+ })
+
+ it('is absent rather than empty when nothing was sent', () => {
+ expect(normalizeEntryPoint(undefined)).toBeUndefined()
+ expect(normalizeEntryPoint('')).toBeUndefined()
+ expect(normalizeEntryPoint(' ')).toBeUndefined()
+ expect(normalizeEntryPoint(42)).toBeUndefined()
+ })
+
+ it('refuses anything that is not a plain key, rather than passing it on', () => {
+ // A query/fragment injection into the authorize URL, whitespace that would split a report row,
+ // and the long strings auth-service would otherwise store up to 255 chars of.
+ expect(normalizeEntryPoint('cli&prompt=none')).toBeUndefined()
+ expect(normalizeEntryPoint('cli desktop')).toBeUndefined()
+ expect(normalizeEntryPoint('cli\ndesktop')).toBeUndefined()
+ expect(normalizeEntryPoint('a'.repeat(65))).toBeUndefined()
+ expect(normalizeEntryPoint('-leading-dash')).toBeUndefined()
+ })
+})
diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts
index cb7d88b6b..311e48b63 100644
--- a/backend/src/routes/auth.ts
+++ b/backend/src/routes/auth.ts
@@ -15,6 +15,7 @@ import {
SsoTokenError,
webCallbackUri,
isLoopbackRedirectUri,
+ normalizeEntryPoint,
resolveWebOrigin,
requestedWebOrigin,
type SsoTx,
@@ -157,7 +158,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
// 1b) Native/desktop-driven login (loopback OAuth). Accepts an explicit loopback redirect_uri so a
// desktop client can run a local HTTP listener to capture the SSO callback; unlike the web
// authorize, it never derives redirect_uri from a web origin. /exchange reuses tx.redirectUri.
- app.post<{ Body: { redirectUri?: string; autonomousEnv?: AutonomousEnvironment } }>(
+ app.post<{ Body: { redirectUri?: string; autonomousEnv?: AutonomousEnvironment; entryPoint?: string } }>(
'/api/auth/authorize-native',
async (req, reply) => {
const redirectUri = typeof req.body?.redirectUri === 'string' ? req.body.redirectUri.trim() : ''
@@ -173,7 +174,10 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
const state = randomState()
const webOrigin = new URL(redirectUri).origin
const tx = await createTx({ verifier, state, next: '/', redirectUri, webOrigin, autonomousEnv })
- return sendSuccess(reply, { authorizeUrl: authorizeUrl(challenge, state, redirectUri, autonomousEnv), tx })
+ // Which surface started this sign-in (`cli`, `desktop`) — analytics only, and dropped
+ // unless it is a plain key, because this route needs no token.
+ const entryPoint = normalizeEntryPoint(req.body?.entryPoint)
+ return sendSuccess(reply, { authorizeUrl: authorizeUrl(challenge, state, redirectUri, autonomousEnv, entryPoint), tx })
} catch {
return sendError(reply, 'login transaction service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 7e73d11ea..7d5274726 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -336,6 +336,7 @@ Machine:
harness login sign in with SSO and save this computer's session
harness login --force stop the daemon and sign in with a different SSO account
harness login --json emit machine-readable NDJSON instead of opening a browser (for GUI clients)
+ harness login --entry-point=desktop record which surface started the sign-in (GUI clients; default cli)
harness auth status --json print {loggedIn,...} for this computer's saved session
harness start start the adapter using the saved SSO session
harness start -f run the adapter in the FOREGROUND (for a supervisor; logs to stdout)
@@ -642,9 +643,12 @@ async function loginCommand(
foreground: boolean,
force: boolean,
json: boolean,
- opts: { chained?: boolean } = {},
+ opts: { chained?: boolean; entryPoint?: string } = {},
): Promise<SignInOutcome> {
if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')
+ // Which surface asked to sign in. A person in a terminal is `cli`; the desktop app runs this same
+ // command and says so with `--entry-point=desktop`. Analytics only — it names no privilege.
+ const entryPoint = opts.entryPoint ?? 'cli'
const emit = (line: Record<string, unknown>): void => { if (json) console.log(JSON.stringify(line)) }
const succeed = async (alreadySignedIn: boolean, installing?: Promise<GridInstallResult>): Promise<SignInOutcome> => {
// `chained` is `harness grid login`, which runs the hand-off itself and reports it as its own
@@ -685,7 +689,7 @@ async function loginCommand(
}
return await succeed(true)
}
- if (!force) return await browserSignIn(json, emit, () => succeed(false))
+ if (!force) return await browserSignIn(json, emit, () => succeed(false), entryPoint)
// A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming
// under its existing socket while this process replaces the durable session — and no NEW daemon
// may come up on the old session in the meantime. The desktop app re-runs `harness start` whenever
@@ -705,7 +709,7 @@ async function loginCommand(
try {
return await withSpawnLock('login', async () => {
await stopDaemonProcess()
- return await browserSignIn(json, emit, () => succeed(false, installing))
+ return await browserSignIn(json, emit, () => succeed(false, installing), entryPoint)
}, {
onWaiting: (owner) => console.error(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),
})
@@ -738,6 +742,7 @@ async function browserSignIn(
json: boolean,
emit: (line: Record<string, unknown>) => void,
succeed: () => Promise<SignInOutcome>,
+ entryPoint: string,
): Promise<SignInOutcome> {
const callback = createServer()
await new Promise<void>((resolve, reject) => {
@@ -755,6 +760,7 @@ async function browserSignIn(
start = await postJson<{ authorizeUrl?: string; tx?: string }>('/api/auth/authorize-native', {
redirectUri,
autonomousEnv: env.AUTONOMOUS_ENV,
+ entryPoint,
})
if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')
} catch (err) {
@@ -6355,6 +6361,10 @@ const [, , cmd, ...rest] = process.argv
const flags = rest.filter((a) => a.startsWith('-'))
const args = rest.filter((a) => !a.startsWith('-'))
const foreground = flags.includes('--foreground') || flags.includes('-f')
+/** `--entry-point=<key>`: one token, so a build of this CLI that predates the flag drops it with
+ * every other unknown flag instead of mistaking `<key>` for a subcommand word. */
+const entryPointFlag = (): string | undefined =>
+ flags.find((f) => f.startsWith('--entry-point='))?.slice('--entry-point='.length) || undefined
const repair = flags.includes('--repair')
/** `argv` with the first occurrence of `token` removed, order otherwise untouched — how a subcommand
@@ -6381,7 +6391,7 @@ switch (cmd) {
orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
case 'login':
- loginCommand(foreground, flags.includes('--force'), flags.includes('--json')).catch(onError)
+ loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), { entryPoint: entryPointFlag() }).catch(onError)
break
case 'auth':
if (args[0] !== 'status') { console.error('Unknown command: auth ' + (args[0] ?? '')); usage(1) }
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index 358e229c1..38ed6f12c 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -82,7 +82,14 @@ class CliLogin implements SignInClient {
final revision = ++_loginRevision;
final Process process;
try {
- process = await _runner.start(['login', '--force', '--json']);
+ // `--entry-point=desktop` tells login tracking this sign-in came from the app rather than a
+ // terminal. One token, so a CLI that predates the flag ignores it like any unknown flag.
+ process = await _runner.start([
+ 'login',
+ '--force',
+ '--json',
+ '--entry-point=desktop',
+ ]);
} catch (error) {
throw CliNotAvailableException('Could not run the harness CLI: $error');
}
diff --git a/desktop/test/cli_login_test.dart b/desktop/test/cli_login_test.dart
index d8f6d12d1..23c10d9b1 100644
--- a/desktop/test/cli_login_test.dart
+++ b/desktop/test/cli_login_test.dart
@@ -10,7 +10,8 @@ class _Runner extends HarnessCliRunner {
final starts = <Completer<Process>>[];
@override
Future<Process> start(List<String> arguments) {
- expect(arguments, ['login', '--force', '--json']);
+ // The entry point rides along so login tracking can tell an app sign-in from a terminal one.
+ expect(arguments, ['login', '--force', '--json', '--entry-point=desktop']);
final start = Completer<Process>();
starts.add(start);
return start.future;