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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(backend): a sign-in names its account and its auth-service client
Dev jacobaf9b916dddfd
diff --git a/backend/src/lib/sso.test.ts b/backend/src/lib/sso.test.tsindex f28a69871..537045b42 100644--- a/backend/src/lib/sso.test.ts+++ b/backend/src/lib/sso.test.ts@@ -7,7 +7,7 @@ const state = vi.hoisted(() => ({vi.mock('./bus.js', () => ({ pub: state }))-import { consumeTx, createTx, refreshAccessToken, SsoTokenError, type SsoTx } from './sso.js'+import { consumeTx, createTx, exchangeCode, refreshAccessToken, SsoTokenError, type SsoTx } from './sso.js'const tx: SsoTx = {verifier: 'verifier',@@ -75,6 +75,34 @@ describe('SSO PKCE transaction store', () => {expect(body.get('client_id')).toBeTruthy()})+ it('exchanges and refreshes as the client the sign-in named, and as the configured one when it named none', async () => {+ // A token belongs to the client it was issued to: auth-service refuses a code or a refresh+ // token presented under another.+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async () => new Response(+ JSON.stringify({ access_token: 'access' }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ))+ vi.stubGlobal('fetch', fetchMock)+ const sentClient = (call: number) => (fetchMock.mock.calls[call]![1]?.body as URLSearchParams).get('client_id')++ await exchangeCode('code', 'verifier', 'http://127.0.0.1:5000/callback', 'prod', 'harness-desktop')+ await refreshAccessToken('refresh', 'prod', 'harness-desktop')+ expect(sentClient(0)).toBe('harness-desktop')+ expect(sentClient(1)).toBe('harness-desktop')++ await exchangeCode('code', 'verifier', 'http://127.0.0.1:5000/callback', 'prod')+ await refreshAccessToken('refresh', 'prod')+ expect(sentClient(2)).toBe(sentClient(3))+ expect(sentClient(2)).not.toBe('harness-desktop')+ })++ it('keeps the named client with the transaction, and refuses one that is not ours', async () => {+ state.eval.mockResolvedValueOnce(JSON.stringify({ ...tx, clientId: 'harness-web' }))+ await expect(consumeTx('named')).resolves.toMatchObject({ clientId: 'harness-web' })+ state.eval.mockResolvedValueOnce(JSON.stringify({ ...tx, clientId: 'someone-else' }))+ await expect(consumeTx('foreign')).resolves.toBeNull()+ })+it('distinguishes invalid refresh tokens from token-service outages', async () => {vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValueOnce(new Response(JSON.stringify({ error: 'invalid_grant' }),diff --git a/backend/src/lib/sso.ts b/backend/src/lib/sso.tsindex 21c0d5384..b304d7006 100644--- a/backend/src/lib/sso.ts+++ b/backend/src/lib/sso.ts@@ -37,13 +37,17 @@ export interface SsoTx {redirectUri: stringwebOrigin: stringautonomousEnv: AutonomousEnvironment+ /** The auth-service client the authorize URL named, which the code exchange has to name again.+ * Absent is the configured one (`SSO_CLIENT_ID`), as every sign-in was before clients were split. */+ clientId?: SsoClientId}function validTx(raw: unknown): raw is SsoTx {const tx = raw as Partial<SsoTx> | nullreturn !!tx && typeof tx.verifier === 'string' && typeof tx.state === 'string' &&typeof tx.next === 'string' && typeof tx.redirectUri === 'string' && typeof tx.webOrigin === 'string' &&- (tx.autonomousEnv === undefined || isAutonomousEnvironment(tx.autonomousEnv))+ (tx.autonomousEnv === undefined || isAutonomousEnvironment(tx.autonomousEnv)) &&+ (tx.clientId === undefined || normalizeSsoClientId(tx.clientId) === tx.clientId)}export async function createTx(tx: SsoTx): Promise<string> {@@ -142,6 +146,55 @@ export function normalizeEntryPoint(raw: unknown): string | undefined {return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(value) ? value : undefined}+/**+ * auth-service's client for each Harness surface: the terminal, the desktop app, the web app and+ * the phone sign in as themselves, so a sign-in is attributed to — and can be configured for — the+ * surface it came from.+ *+ * ⚠️ A token belongs to the client it was issued to: the code exchange and every later refresh+ * must name the SAME client, or auth-service refuses them. So a client that names one here keeps+ * it with its session and sends it again on `/api/auth/refresh`; one that names none (every build+ * from before this) stays on the configured `SSO_CLIENT_ID` end to end.+ */+export const SSO_CLIENT_IDS = ['harness-cli', 'harness-desktop', 'harness-web', 'harness-mobile'] as const+export type SsoClientId = (typeof SSO_CLIENT_IDS)[number]++/** An allowlist, like [normalizeSignInProvider]: the routes that take it need no token. */+export function normalizeSsoClientId(raw: unknown): SsoClientId | undefined {+ return typeof raw === 'string' ? SSO_CLIENT_IDS.find((id) => id === raw.trim()) : undefined+}++/** The client a request signs in as, and its secret — which is the configured client's alone. */+function ssoClient(autonomousEnv: AutonomousEnvironment, clientId?: SsoClientId): { id: string; secret?: string } {+ const config = autonomousEnvironmentConfig(autonomousEnv)+ const id = clientId ?? config.ssoClientId+ return { id, ...(id === config.ssoClientId && config.ssoClientSecret ? { secret: config.ssoClientSecret } : {}) }+}++/** The accounts a sign-in can go straight to: the two buttons every Harness client shows. */+export const SIGN_IN_PROVIDERS = ['google', 'apple'] as const+export type SignInProvider = (typeof SIGN_IN_PROVIDERS)[number]++/**+ * Which of [SIGN_IN_PROVIDERS] the person pressed, or nothing — and nothing is the sign-in page's+ * own chooser, which is what every client sent before the buttons moved into the app.+ *+ * An allowlist for the reason [normalizeEntryPoint] is a pattern: both authorize routes need no+ * token and this value goes into the authorize URL's query.+ */+export function normalizeSignInProvider(raw: unknown): SignInProvider | undefined {+ if (typeof raw !== 'string') return undefined+ const value = raw.trim().toLowerCase()+ return SIGN_IN_PROVIDERS.find((provider) => provider === value)+}++/** What an authorize URL carries beyond the OAuth request itself. All optional, all plain keys. */+export interface AuthorizeHints {+ entryPoint?: string+ provider?: SignInProvider+ clientId?: SsoClientId+}+/** 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(@@ -149,12 +202,12 @@ export function authorizeUrl(state: string,redirectUri: string,autonomousEnv: AutonomousEnvironment,- entryPoint?: string,+ { entryPoint, provider, clientId }: AuthorizeHints = {},): string {const config = autonomousEnvironmentConfig(autonomousEnv)const u = new URL('/oauth2/authorize', config.ssoIssuer)u.searchParams.set('response_type', 'code')- u.searchParams.set('client_id', config.ssoClientId)+ u.searchParams.set('client_id', ssoClient(autonomousEnv, clientId).id)u.searchParams.set('redirect_uri', redirectUri)u.searchParams.set('scope', env.SSO_SCOPE)u.searchParams.set('code_challenge', challenge)@@ -162,6 +215,8 @@ export function authorizeUrl(u.searchParams.set('state', state)if (env.SSO_PROMPT) u.searchParams.set('prompt', env.SSO_PROMPT)if (entryPoint) u.searchParams.set('entry_point', entryPoint)+ // auth-service opens that account's own sign-in instead of its chooser.+ if (provider) u.searchParams.set('provider', provider)return u.toString()}@@ -193,11 +248,14 @@ export class SsoTokenError extends Error {}async function requestTokens(- body: URLSearchParams,+ grant: Record<string, string>,autonomousEnv: AutonomousEnvironment,+ clientId?: SsoClientId,): Promise<SsoTokens> {const config = autonomousEnvironmentConfig(autonomousEnv)- if (config.ssoClientSecret) body.set('client_secret', config.ssoClientSecret)+ const client = ssoClient(autonomousEnv, clientId)+ const body = new URLSearchParams({ ...grant, client_id: client.id })+ if (client.secret) body.set('client_secret', client.secret)let res: Responsetry {@@ -233,27 +291,24 @@ export async function exchangeCode(verifier: string,redirectUri: string,autonomousEnv: AutonomousEnvironment,+ clientId?: SsoClientId,): Promise<SsoTokens> {- const config = autonomousEnvironmentConfig(autonomousEnv)- const body = new URLSearchParams({+ return requestTokens({grant_type: 'authorization_code',code,- redirect_uri: redirectUri, // MUST match the one sent to /authorize- client_id: config.ssoClientId,+ redirect_uri: redirectUri, // MUST match the one sent to /authorize — as must the clientcode_verifier: verifier,- })- return requestTokens(body, autonomousEnv)+ }, autonomousEnv, clientId)}/** Exchange a browser-held refresh token for a fresh SSO access token. */export async function refreshAccessToken(refreshToken: string,autonomousEnv: AutonomousEnvironment,+ clientId?: SsoClientId,): Promise<SsoTokens> {- const config = autonomousEnvironmentConfig(autonomousEnv)- return requestTokens(new URLSearchParams({+ return requestTokens({grant_type: 'refresh_token',refresh_token: refreshToken,- client_id: config.ssoClientId,- }), autonomousEnv)+ }, autonomousEnv, clientId)}diff --git a/backend/src/lib/ssoProvider.test.ts b/backend/src/lib/ssoProvider.test.tsnew file mode 100644index 000000000..c05ddf906--- /dev/null+++ b/backend/src/lib/ssoProvider.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest'+import { authorizeUrl, normalizeSignInProvider, normalizeSsoClientId } from './sso.js'++/**+ * `provider` is which button the person pressed: Continue with Google, Continue with Apple. Both+ * authorize routes need no token and the value goes into the authorize URL's query, so only the+ * two names this product sends are passed on.+ */+describe('sign-in provider', () => {+ it('keeps the two accounts the clients offer', () => {+ expect(normalizeSignInProvider('google')).toBe('google')+ expect(normalizeSignInProvider('apple')).toBe('apple')+ })++ it('trims and lowercases', () => {+ expect(normalizeSignInProvider(' Google ')).toBe('google')+ expect(normalizeSignInProvider('APPLE\n')).toBe('apple')+ })++ it('is absent for anything else, which is the sign-in page\'s own chooser', () => {+ expect(normalizeSignInProvider(undefined)).toBeUndefined()+ expect(normalizeSignInProvider('')).toBeUndefined()+ expect(normalizeSignInProvider('sso')).toBeUndefined()+ expect(normalizeSignInProvider('github')).toBeUndefined()+ expect(normalizeSignInProvider('google&prompt=none')).toBeUndefined()+ expect(normalizeSignInProvider(42)).toBeUndefined()+ })+})++describe('SSO client', () => {+ it('keeps the four surfaces\' own clients', () => {+ for (const id of ['harness-cli', 'harness-desktop', 'harness-web', 'harness-mobile']) {+ expect(normalizeSsoClientId(id)).toBe(id)+ }+ })++ it('is absent for anything else, which is the configured client', () => {+ expect(normalizeSsoClientId(undefined)).toBeUndefined()+ expect(normalizeSsoClientId('')).toBeUndefined()+ expect(normalizeSsoClientId('harness-admin')).toBeUndefined()+ expect(normalizeSsoClientId('harness-cli&scope=admin')).toBeUndefined()+ expect(normalizeSsoClientId(7)).toBeUndefined()+ })+})++describe('authorize URL', () => {+ const url = (hints?: Parameters<typeof authorizeUrl>[4]) =>+ new URL(authorizeUrl('challenge', 'state', 'http://127.0.0.1:5000/callback', 'prod', hints))++ it('names the provider and the entry point when the client sent them', () => {+ const { searchParams } = url({ entryPoint: 'desktop', provider: 'apple' })+ expect(searchParams.get('provider')).toBe('apple')+ expect(searchParams.get('entry_point')).toBe('desktop')+ expect(searchParams.get('code_challenge')).toBe('challenge')+ })++ it('carries neither for a client that sent none, as before the buttons existed', () => {+ const { searchParams } = url()+ expect(searchParams.has('provider')).toBe(false)+ expect(searchParams.has('entry_point')).toBe(false)+ expect(searchParams.get('state')).toBe('state')+ })++ it('signs in as the surface that asked, or as the configured client', () => {+ expect(url({ clientId: 'harness-mobile' }).searchParams.get('client_id')).toBe('harness-mobile')+ const configured = url().searchParams.get('client_id')+ expect(configured).toBeTruthy()+ expect(configured).not.toBe('harness-mobile')+ })+})diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.tsindex 369f15934..86202e1f8 100644--- a/backend/src/routes/auth.ts+++ b/backend/src/routes/auth.ts@@ -16,6 +16,8 @@ import {webCallbackUri,isLoopbackRedirectUri,normalizeEntryPoint,+ normalizeSignInProvider,+ normalizeSsoClientId,resolveWebOrigin,requestedWebOrigin,type SsoTx,@@ -28,7 +30,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {// 1) Start login (web-driven). The web fetches this (XHR, so the API URL never hits the address// bar), stashes the returned opaque `tx` id in sessionStorage, and navigates the browser to// `authorizeUrl` (the SSO provider). redirect_uri is the WEB callback page, not the API.- app.post<{ Body: { next?: string; origin?: string; autonomousEnv?: AutonomousEnvironment } }>('/api/auth/authorize', async (req, reply) => {+ app.post<{ Body: { next?: string; origin?: string; autonomousEnv?: AutonomousEnvironment; provider?: string; clientId?: string } }>('/api/auth/authorize', async (req, reply) => {const { verifier, challenge } = pkcePair()const state = randomState()const next = typeof req.body?.next === 'string' && req.body.next ? req.body.next : '/'@@ -38,9 +40,13 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {try { autonomousEnv = parseAutonomousEnvironment(req.body?.autonomousEnv) } catch {return sendError(reply, 'invalid Autonomous environment', 'INVALID_AUTONOMOUS_ENV', 400)}+ // Which button the person pressed (Google, Apple); absent is the sign-in page's own chooser.+ const provider = normalizeSignInProvider(req.body?.provider)+ // Which surface is signing in (lib/sso.ts `SSO_CLIENT_IDS`), kept for the exchange.+ const clientId = normalizeSsoClientId(req.body?.clientId)try {- const tx = await createTx({ verifier, state, next, redirectUri, webOrigin, autonomousEnv })- return sendSuccess(reply, { authorizeUrl: authorizeUrl(challenge, state, redirectUri, autonomousEnv), tx })+ const tx = await createTx({ verifier, state, next, redirectUri, webOrigin, autonomousEnv, ...(clientId ? { clientId } : {}) })+ return sendSuccess(reply, { authorizeUrl: authorizeUrl(challenge, state, redirectUri, autonomousEnv, { provider, clientId }), tx })} catch {return sendError(reply, 'login transaction service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)}@@ -64,7 +70,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {return sendError(reply, 'invalid_state', 'INVALID_STATE', 400)}try {- const tokens = await exchangeCode(code, tx.verifier, tx.redirectUri, tx.autonomousEnv)+ const tokens = await exchangeCode(code, tx.verifier, tx.redirectUri, tx.autonomousEnv, tx.clientId)const token = tokens.access_tokenif (!token) throw new Error('sso response had no access_token')const user = await authenticateAccessToken(token, tx.autonomousEnv)@@ -79,6 +85,10 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {token,next: tx.next,autonomousEnv: tx.autonomousEnv,+ // The client these tokens were issued to, for the caller to keep and name on every+ // refresh. Absent is the configured client — and what a backend from before the+ // clients were split answers, so a caller never assumes the client it asked for.+ ...(tx.clientId ? { clientId: tx.clientId } : {}),...(tokens.refresh_token ? { refreshToken: tokens.refresh_token } : {}),...(typeof tokens.expires_in === 'number' ? { expiresIn: tokens.expires_in } : {}),})@@ -102,7 +112,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {},)- app.post<{ Body: { refreshToken?: string; autonomousEnv?: AutonomousEnvironment } }>(+ app.post<{ Body: { refreshToken?: string; autonomousEnv?: AutonomousEnvironment; clientId?: string } }>('/api/auth/refresh',async (req, reply) => {const refreshToken = typeof req.body?.refreshToken === 'string' ? req.body.refreshToken.trim() : ''@@ -126,7 +136,8 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {}try {- const tokens = await refreshAccessToken(refreshToken, autonomousEnv)+ // The client the session was issued to: a refresh under any other is refused upstream.+ const tokens = await refreshAccessToken(refreshToken, autonomousEnv, normalizeSsoClientId(req.body?.clientId))const token = tokens.access_tokenif (!token) throw new SsoTokenError('SSO refresh returned no access token', 'TOKEN_SERVICE_UNAVAILABLE')const user = await authenticateAccessToken(token, autonomousEnv)@@ -172,7 +183,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; entryPoint?: string } }>(+ app.post<{ Body: { redirectUri?: string; autonomousEnv?: AutonomousEnvironment; entryPoint?: string; provider?: string; clientId?: string } }>('/api/auth/authorize-native',async (req, reply) => {const redirectUri = typeof req.body?.redirectUri === 'string' ? req.body.redirectUri.trim() : ''@@ -187,11 +198,13 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {const { verifier, challenge } = pkcePair()const state = randomState()const webOrigin = new URL(redirectUri).origin- const tx = await createTx({ verifier, state, next: '/', redirectUri, webOrigin, autonomousEnv })+ const clientId = normalizeSsoClientId(req.body?.clientId)+ const tx = await createTx({ verifier, state, next: '/', redirectUri, webOrigin, autonomousEnv, ...(clientId ? { clientId } : {}) })// 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 })+ const provider = normalizeSignInProvider(req.body?.provider)+ return sendSuccess(reply, { authorizeUrl: authorizeUrl(challenge, state, redirectUri, autonomousEnv, { entryPoint, provider, clientId }), tx })} catch {return sendError(reply, 'login transaction service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)}diff --git a/backend/src/routes/machines.ts b/backend/src/routes/machines.tsindex fc0cf762e..ae06f285c 100644--- a/backend/src/routes/machines.ts+++ b/backend/src/routes/machines.ts@@ -66,7 +66,7 @@ function requestAccessToken(authorization: string | undefined): string {// (lib/autonomousBff.ts). A session Harness issued itself — a phone, or a computer signed in by// scanning its QR — means nothing to that service: say what to do instead of a 502 from upstream.if (isHarnessAccessToken(token)) {- throw new AppError('Billing needs your Autonomous sign-in. Sign in with SSO on this device (harness login --sso).', 403, 'NEEDS_AUTONOMOUS_SIGN_IN')+ throw new AppError('Billing needs your Autonomous sign-in. Sign in with Google or Apple on this device (harness login --force).', 403, 'NEEDS_AUTONOMOUS_SIGN_IN')}return token}