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
Auth: sign in through SSO once, then hold a Harness session (CLI and Desktop) (#1979)
0xken15c4e2b6fb2075
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex afb277527..25b04484f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1668,6 +1668,20 @@ model HarnessSession {/// Slides forward on every refresh: a phone in use stays signed in, one left in a drawer does not.expiresAt DateTimerevokedAt DateTime?+ /// A session an SSO sign-in backs (lib/ssoSession.ts): the CLI or Desktop signed in through SSO and traded it for this+ /// session. The person's SSO refresh token, and the last access token it gave, encrypted (lib/machineCredential.ts);+ /// cleared when the session ends. Absent on a session a QR or a handoff made.+ ssoRefresh String?+ ssoAccess String?+ ssoAccessExpiresAt DateTime?+ /// The account plane and auth-service client the SSO tokens were issued on: a renewal must name the same.+ ssoEnv String?+ ssoClientId String?+ /// The last time SSO accepted the sign-in: re-checked hourly, and the outage grace runs from it.+ ssoCheckedAt DateTime?+ /// Set before a renewal asks SSO, cleared once its answer is saved. Left set, a renewal was lost on the way — its+ /// rotated refresh token may never have been saved — so a refusal of the stored one is no proof of a sign-out.+ ssoRenewingAt DateTime?@@index([userId])@@map("harness_sessions")diff --git a/backend/src/lib/deviceKeyLog.test.ts b/backend/src/lib/deviceKeyLog.test.tsindex 4510efe82..8f414e78b 100644--- a/backend/src/lib/deviceKeyLog.test.ts+++ b/backend/src/lib/deviceKeyLog.test.ts@@ -174,7 +174,7 @@ describe('appendDeviceKey', () => {await appendDeviceKey(USER, await addEntry(box2, 'machine', MID2, 'box2'), { kind: 'machine', machineId: MID2, harnessSessionId: 'sess-qr' })await appendDeviceKey(USER, await removeEntry(box2.pub, box1), { kind: 'machine', machineId: MID1 })expect(m.publishDown).toHaveBeenCalledWith(MID2, expect.objectContaining({ frame: expect.objectContaining({ type: 'machine_revoked' }) }))- expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-qr', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date) } })+ expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-qr', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date), expiresAt: expect.any(Date), ssoRefresh: null, ssoAccess: null, ssoAccessExpiresAt: null, ssoRenewingAt: null } })})it('refuses a machine signing a removal with another machine key', async () => {@@ -206,7 +206,7 @@ describe('appendDeviceKey', () => {await appendDeviceKey(USER, await addEntry(phone, 'viewer', '', 'phone'), { kind: 'viewer', harnessSessionId: 'sess-1' })await appendDeviceKey(USER, await addEntry(box1, 'machine', MID1, 'box1'), { kind: 'machine', machineId: MID1 })await appendDeviceKey(USER, await removeEntry(phone.pub, box1), { kind: 'machine', machineId: MID1 })- expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-1', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date) } })+ expect(m.revoke).toHaveBeenCalledWith({ where: { id: 'sess-1', userId: USER, OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }, data: { revokedAt: expect.any(Date), expiresAt: expect.any(Date), ssoRefresh: null, ssoAccess: null, ssoAccessExpiresAt: null, ssoRenewingAt: null } })expect(m.publishDown).not.toHaveBeenCalled()})diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.tsindex 4386386f7..7c3c0592d 100644--- a/backend/src/lib/harnessSession.ts+++ b/backend/src/lib/harnessSession.ts@@ -7,6 +7,15 @@ import { TEAM_CONVERTED_FRAME } from './teamSession.js'import { userService } from '../services/UserService.js'import { storedAutonomousEnvironment, type AutonomousEnvironment } from './autonomousEnvironment.js'import { SsoAuthError, type AuthUser } from './ssoAuth.js'+import type { SsoClientId } from './sso.js'+import {+ endedSessionData,+ recheckSsoSession,+ ssoSessionData,+ ssoSignInAgainError,+ type SsoGrant,+ type SsoSessionRequest,+} from './ssoSession.js'import {HARNESS_ACCESS_PREFIX,HARNESS_HANDOFF_PREFIX,@@ -195,8 +204,25 @@ async function computerHeldByAnotherSignIn(userId: string, computerId: string):return rows.some((row) => row.sessionKind !== 'team')}+/**+ * A session for [userId] that their SSO sign-in [grant] backs (lib/ssoSession.ts): what the CLI and Desktop trade an SSO+ * sign-in for. It names no computer, whatever its kind. Null when the account is gone; throws when it cannot be stored.+ */+export async function createSsoSession(+ userId: string,+ { kind, label }: SsoSessionRequest,+ grant: SsoGrant,+ autonomousEnv: AutonomousEnvironment,+ clientId?: SsoClientId,+): Promise<HarnessTokens | null> {+ return createSession(userId, label, kind, undefined, undefined, ssoSessionData(grant, autonomousEnv, clientId))+}+/** A new session for [userId]: a refresh token (stored hashed) and its first access token. */-async function createSession(userId: string, label: string, kind: HarnessSessionKind, computerId?: string, hostMachineId?: string): Promise<HarnessTokens | null> {+async function createSession(+ userId: string, label: string, kind: HarnessSessionKind, computerId?: string, hostMachineId?: string,+ sso?: ReturnType<typeof ssoSessionData>,+): Promise<HarnessTokens | null> {const user = await userService.get(userId)if (!user) return nullconst refreshToken = newHarnessToken(kind === 'team' ? HARNESS_TEAM_REFRESH_PREFIX : HARNESS_REFRESH_PREFIX)@@ -210,6 +236,7 @@ async function createSession(userId: string, label: string, kind: HarnessSession...(kind !== 'viewer' && computerId ? { computerId } : {}),// A team session's Mac, which its machine records (MachineService.resolveForTeamComputer)....(kind === 'team' && hostMachineId ? { hostMachineId } : {}),+ ...(sso ?? {}),expiresAt: sessionExpiry(),},})@@ -224,7 +251,9 @@ async function createSession(userId: string, label: string, kind: HarnessSession/*** A new access token for the session [refreshToken] belongs to, or null when that session is gone- * (unknown, revoked, idle past its lifetime, or its user deleted) — the caller's 401.+ * (unknown, revoked, idle past its lifetime, its user deleted, or its SSO sign-in ended) — the caller's 401.+ * A session an SSO sign-in backs is re-checked with SSO first (lib/ssoSession.ts); one SSO has not confirmed+ * within its grace throws `SIGN_IN_AGAIN` — shown as "Sign in again", the session itself kept.** The refresh token is not rotated. Rotation is only as good as its reuse detection, and a phone* that loses the response to a refresh would then present the old token and be signed out for a@@ -240,10 +269,15 @@ export async function refreshHarnessSession(refreshToken: string): Promise<Harneif ((session.kind === 'team') !== isTeamRefreshToken(refreshToken)) return nullconst user = await userService.get(session.userId)if (!user) return null- await prisma.harnessSession.update({- where: { id: session.id },+ const sso = await recheckSsoSession(session)+ if (sso === 'ended') return null+ if (sso === 'sign-in-again') throw ssoSignInAgainError()+ // Only a session still live moves on: one signed out meanwhile stays ended, and gets no new access token.+ const { count } = await prisma.harnessSession.updateMany({+ where: { id: session.id, ...notRevoked },data: { lastUsedAt: new Date(), expiresAt: sessionExpiry() },})+ if (count === 0) return nullreturn {token: await issueAccess(session.id, session.userId, session.kind === 'team' ? 'team' : 'viewer'),expiresIn: HARNESS_ACCESS_TTL_SEC,@@ -251,12 +285,13 @@ export async function refreshHarnessSession(refreshToken: string): Promise<Harne}}-/** Sign out: the session's refresh token stops working, and so, at once, does its access token. */+/** Sign out: the session's refresh token stops working, and so, at once, does its access token. Any SSO+ * tokens it held are deleted. */export async function revokeHarnessSession(refreshToken: string): Promise<void> {if (!isHarnessRefreshToken(refreshToken)) returnawait prisma.harnessSession.updateMany({where: { refreshHash: harnessTokenHash(refreshToken), ...notRevoked },- data: { revokedAt: new Date() },+ data: endedSessionData(),})}@@ -321,7 +356,7 @@ export async function authenticateHarnessAccessToken(token: string): Promise<Aut/** Revoke the session with this id (a device removed from the account's device key log). */export async function revokeHarnessSessionById(sessionId: string, userId: string): Promise<void> {- await prisma.harnessSession.updateMany({ where: { id: sessionId, userId, ...notRevoked }, data: { revokedAt: new Date() } })+ await prisma.harnessSession.updateMany({ where: { id: sessionId, userId, ...notRevoked }, data: endedSessionData() })}// ── Sign in a computer by scanning its QR with a signed-in phone ──────────────────────────────────diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.tsindex b2456defc..5098e350c 100644--- a/backend/src/lib/ssoAuth.ts+++ b/backend/src/lib/ssoAuth.ts@@ -41,7 +41,9 @@ export class SsoAuthError extends Error {constructor(message: string,readonly code: 'INVALID_TOKEN' | 'AUTH_SERVICE_UNAVAILABLE' | 'AUTONOMOUS_ENV_MISMATCH' | 'AUTONOMOUS_ENV_NOT_ALLOWED'- | 'TEAM_SESSION_LIMITED',+ | 'TEAM_SESSION_LIMITED'+ /** A Harness session SSO has not confirmed for longer than its grace (lib/ssoSession.ts): sign in again. */+ | 'SIGN_IN_AGAIN',readonly requiredEnv?: AutonomousEnvironment,) {super(message)diff --git a/backend/src/lib/ssoSession.test.ts b/backend/src/lib/ssoSession.test.tsnew file mode 100644index 000000000..5851ac9d8--- /dev/null+++ b/backend/src/lib/ssoSession.test.ts@@ -0,0 +1,648 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'++// Harness sessions an SSO sign-in backs (lib/ssoSession.ts): the CLI and Desktop sign in through SSO once and then+// hold a Harness session, while the backend keeps the person's SSO refresh token and re-checks it hourly.+//+// Redis, the sessions collection and the account service's token endpoint are faked; everything between them —+// the routes, the session code, the encryption, the SSO identity check — is the real code.+const fakes = vi.hoisted(() => {+ const redis = new Map<string, string>()+ const sessions: Array<Record<string, unknown> & { id: string }> = []+ const users = new Map<string, Record<string, unknown>>()+ let failCreate = false+ const field = (s: Record<string, unknown>, k: string, v: unknown): boolean => {+ if (v !== null && typeof v === 'object' && 'isSet' in v) return (k in s && s[k] !== undefined) === (v as { isSet: boolean }).isSet+ if (v === null) return s[k] === null || s[k] === undefined+ return k in s && s[k] === v+ }+ const matches = (s: Record<string, unknown>, w: Record<string, unknown>): boolean => Object.entries(w).every(([k, v]) =>+ k === 'OR' ? (v as Record<string, unknown>[]).some((o) => matches(s, o)) : field(s, k, v))+ const pub = {+ set: vi.fn(async (key: string, value: string, ...args: unknown[]) => {+ if (args.includes('NX') && redis.has(key)) return null+ redis.set(key, value); return 'OK'+ }),+ get: vi.fn(async (key: string) => redis.get(key) ?? null),+ del: vi.fn(async (key: string) => (redis.delete(key) ? 1 : 0)),+ // The lock's compare-and-delete (lib/ssoSession.ts RELEASE_SCRIPT).+ eval: vi.fn(async (_script: string, _n: number, key: string, owner: string) => (redis.get(key) === owner && redis.delete(key) ? 1 : 0)),+ multi: vi.fn(() => {+ const ops: Array<() => unknown> = []+ const chain = {+ get: (key: string) => { ops.push(() => redis.get(key) ?? null); return chain },+ del: (key: string) => { ops.push(() => (redis.delete(key) ? 1 : 0)); return chain },+ exec: async () => ops.map((op) => [null, op()]),+ }+ return chain+ }),+ }+ const harnessSession = {+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {+ if (failCreate) throw new Error('mongo down')+ const row = { id: `s${sessions.length + 1}`, createdAt: new Date(), lastUsedAt: new Date(), ...data }+ sessions.push(row); return row+ }),+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => sessions.find((s) => matches(s, where)) ?? null),+ update: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {+ const row = sessions.find((s) => matches(s, where)); if (!row) throw new Error('no row'); Object.assign(row, data); return row+ }),+ updateMany: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {+ const rows = sessions.filter((s) => matches(s, where)); rows.forEach((r) => Object.assign(r, data)); return { count: rows.length }+ }),+ }+ const machine = { findMany: vi.fn(async () => []), findFirst: vi.fn(async () => null), updateMany: vi.fn(async () => ({ count: 0 })) }+ // The account service's token endpoint: which refresh tokens it still honours, and what it answers.+ const sso = {+ live: new Map<string, string>(), // refresh token → the account's email+ rotate: true,+ down: false,+ calls: 0,+ counter: 0,+ /** While set, the token endpoint holds every answer until it settles: a renewal in flight. */+ gate: null as Promise<void> | null,+ }+ const logLines: string[] = []+ return {+ redis, sessions, users, pub, harnessSession, machine, sso, logLines,+ setFailCreate: (v: boolean) => { failCreate = v },+ get: vi.fn(async (id: string) => users.get(id) ?? null),+ }+})++vi.mock('./bus.js', () => ({ pub: fakes.pub, publishDown: vi.fn(async () => 1) }))+vi.mock('./deviceKeyLog.js', () => ({ activeMachineKeys: vi.fn(async () => []) }))+vi.mock('./googleSubject.js', () => ({ scheduleGoogleSubjectFill: vi.fn() }))+vi.mock('./prisma.js', () => ({+ prisma: { harnessSession: fakes.harnessSession, machine: fakes.machine, $transaction: vi.fn(async (body: (tx: unknown) => unknown) =>+ body({ harnessSession: fakes.harnessSession, machine: fakes.machine })) },+ machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },+}))+const userService = vi.hoisted(() => ({+ get: (id: string) => fakes.get(id),+ findByEmail: vi.fn(async (email: string) => [...fakes.users.values()].find((u) => u.email === email) ?? null),+ findByExternal: vi.fn(async () => null),+ upsertFromSso: vi.fn(async ({ email }: { email: string }) => [...fakes.users.values()].find((u) => u.email === email)),+ recordSignInAttribution: vi.fn(async () => undefined),+ toPublic: (u: unknown) => u,+}))+vi.mock('../services/UserService.js', () => ({+ userService,+ normalizeUserEmail: (email: string) => email.trim().toLowerCase(),+ isProvisionalUserEmail: () => false,+}))+vi.mock('../services/index.js', () => ({ userService }))+// Every log line, as text, so no test can miss a token written into one.+vi.mock('../utils/logger.js', () => {+ const line = (level: string) => (message: string, ...rest: unknown[]) => {+ fakes.logLines.push(`${level} ${message} ${rest.map((r) => (r instanceof Error ? `${r.message} ${r.stack}` : JSON.stringify(r))).join(' ')}`)+ }+ return { logger: { debug: line('debug'), info: line('info'), warn: line('warn'), error: line('error') } }+})+// The account service's token endpoint (lib/sso.ts requestTokens), as the fake above decides.+vi.mock('./sso.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./sso.js')>()+ const grant = (email: string) => {+ fakes.sso.counter+++ const access = `sso-access-${fakes.sso.counter}`+ accessEmails.set(access, email)+ return { access_token: access, expires_in: 3600 }+ }+ const accessEmails = new Map<string, string>()+ ;(globalThis as { __ssoAccessEmails?: Map<string, string> }).__ssoAccessEmails = accessEmails+ return {+ ...actual,+ consumeTx: vi.fn(async (tx: string) => (tx === 'tx-1'+ ? { verifier: 'v', state: 'st', next: '/', redirectUri: 'http://127.0.0.1:1/cb', webOrigin: 'http://127.0.0.1:1', autonomousEnv: 'prod', clientId: 'harness-cli' }+ : null)),+ exchangeCode: vi.fn(async (code: string) => {+ if (code !== 'code-dee') throw new actual.SsoTokenError('bad code', 'INVALID_GRANT')+ const refresh = `sso-refresh-${fakes.sso.counter + 1}`+ fakes.sso.live.set(refresh, '[email protected]')+ return { ...grant('[email protected]'), refresh_token: refresh }+ }),+ refreshAccessToken: vi.fn(async (refreshToken: string) => {+ fakes.sso.calls+++ if (fakes.sso.gate) await fakes.sso.gate+ if (fakes.sso.down) throw new actual.SsoTokenError('SSO token service unavailable', 'TOKEN_SERVICE_UNAVAILABLE')+ const email = fakes.sso.live.get(refreshToken)+ if (!email) throw new actual.SsoTokenError('SSO token endpoint returned 400', 'INVALID_GRANT')+ const tokens: Record<string, unknown> = grant(email)+ if (fakes.sso.rotate) {+ fakes.sso.live.delete(refreshToken)+ const next = `sso-refresh-${fakes.sso.counter}-r`+ fakes.sso.live.set(next, email)+ tokens.refresh_token = next+ }+ return tokens+ }),+ }+})++import { clearSsoProfileCache, authenticateAccessToken, resetSsoBreakers, SsoAuthError } from './ssoAuth.js'+import { refreshHarnessSession, revokeHarnessSession } from './harnessSession.js'+import { decryptMachineCredential } from './machineCredential.js'+import { SSO_OUTAGE_GRACE_MS, SSO_RECHECK_MS, ensureHarnessSessionExpiry, ssoAccessTokenFor } from './ssoSession.js'+import { authRoutes } from '../routes/auth.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'++const USER = { id: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod', externalId: 'ext-dee' }+const HOUR = 60 * 60_000++// The profile service answers for the SSO access tokens the fake token endpoint issued.+function stubProfileService(): void {+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {+ const auth = String((init?.headers as Record<string, string>)?.Authorization ?? '')+ const email = (globalThis as { __ssoAccessEmails?: Map<string, string> }).__ssoAccessEmails!.get(auth.replace(/^Bearer /, ''))+ if (!email) return new Response('{}', { status: 401 })+ return new Response(JSON.stringify({ status: 1, data: { id: 'ext-dee', email } }), { status: 200 })+ })+}++let app: FastifyInstance++beforeEach(async () => {+ vi.useRealTimers()+ fakes.redis.clear(); fakes.sessions.length = 0; fakes.users.clear(); fakes.logLines.length = 0+ fakes.users.set(USER.id, USER)+ fakes.sso.live.clear(); fakes.sso.rotate = true; fakes.sso.down = false; fakes.sso.calls = 0; fakes.sso.counter = 0; fakes.sso.gate = null+ fakes.setFailCreate(false)+ clearSsoProfileCache()+ // The profile service's circuit (lib/ssoAuth.ts) is shared: tests that fail it on purpose must not open it for the next.+ resetSsoBreakers()+ vi.clearAllMocks()+ stubProfileService()+ app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app, authenticateAccessToken)+ await app.register(authRoutes)+ await app.ready()+})++afterEach(async () => {+ vi.useRealTimers()+ vi.restoreAllMocks()+ await app.close()+})++const ASK_COMPUTER = { kind: 'computer', label: 'Dee’s Mac' }++/** Sign in through SSO as today's CLI does, asking (or not) for a Harness session. */+async function signIn(harnessSession?: unknown) {+ const res = await app.inject({ method: 'POST', url: '/api/auth/exchange', payload: {+ code: 'code-dee', state: 'st', tx: 'tx-1', ...(harnessSession ? { harnessSession } : {}),+ } })+ return { status: res.statusCode, data: res.json().data as Record<string, unknown> }+}++async function refresh(refreshToken: unknown, extra: Record<string, unknown> = {}) {+ const res = await app.inject({ method: 'POST', url: '/api/auth/refresh', payload: { refreshToken, autonomousEnv: 'prod', ...extra } })+ return { status: res.statusCode, body: res.json() as { data?: Record<string, unknown>; error?: { code?: string; message?: string } } }+}++async function me(token: unknown) {+ return (await app.inject({ method: 'GET', url: '/api/auth/me', headers: { authorization: `Bearer ${String(token)}` } })).statusCode+}++describe('signing in: SSO once, then a Harness session', () => {+ it('trades the SSO sign-in for a Harness computer session and keeps the SSO refresh token on the server, encrypted', async () => {+ const { status, data } = await signIn(ASK_COMPUTER)+ expect(status).toBe(200)+ expect(data.token).toMatch(/^hna_/)+ expect(data.refreshToken).toMatch(/^hnr_/)+ expect(data).toMatchObject({ kind: 'computer', expiresIn: 3600, autonomousEnv: 'prod', harnessSession: true })+ // The SSO tokens never reach the client.+ expect(JSON.stringify(data)).not.toMatch(/sso-/)++ const [row] = fakes.sessions+ expect(row).toMatchObject({ userId: USER.id, kind: 'computer', label: 'Dee’s Mac', ssoEnv: 'prod', ssoClientId: 'harness-cli' })+ // Naming no computer: this session is never "the computer's own sign-in" (routes/auth.ts isThisComputer).+ expect(row.computerId).toBeUndefined()+ expect(String(row.ssoRefresh)).not.toContain('sso-refresh')+ expect(decryptMachineCredential(String(row.ssoRefresh))).toBe('sso-refresh-1')+ expect(row.ssoCheckedAt).toBeInstanceOf(Date)++ // The Harness tokens work, and refresh without asking SSO.+ expect(await me(data.token)).toBe(200)+ const renewed = await refresh(data.refreshToken)+ expect(renewed.status).toBe(200)+ expect(renewed.body.data!.token).toMatch(/^hna_/)+ expect(fakes.sso.calls).toBe(0)+ })++ it('answers a sign-in that asks for nothing exactly as before: the SSO tokens', async () => {+ const { status, data } = await signIn()+ expect(status).toBe(200)+ expect(data).toMatchObject({ token: 'sso-access-1', refreshToken: 'sso-refresh-1' })+ expect(data.harnessSession).toBeUndefined()+ expect(fakes.sessions).toHaveLength(0)+ })++ it('a Desktop with no CLI asks for a viewer session, which may not connect as a machine', async () => {+ const { data } = await signIn({ kind: 'viewer', label: 'Desktop' })+ expect(data.kind).toBe('viewer')+ await expect(authenticateAccessToken(String(data.token), 'prod', { allowHarnessSession: 'computer' }))+ .rejects.toMatchObject({ code: 'INVALID_TOKEN' })+ })++ it('refuses to make anything else, and never a team session', async () => {+ for (const ask of [{ kind: 'team', label: 'x' }, { kind: 'computer', label: 7 }, 'computer']) {+ const res = await app.inject({ method: 'POST', url: '/api/auth/exchange', payload: { code: 'code-dee', state: 'st', tx: 'tx-1', harnessSession: ask } })+ expect(res.statusCode).toBe(400)+ }+ expect(fakes.sessions).toHaveLength(0)+ })++ it('still signs in with the SSO tokens when the session cannot be made', async () => {+ fakes.setFailCreate(true)+ const { status, data } = await signIn(ASK_COMPUTER)+ expect(status).toBe(200)+ expect(data).toMatchObject({ token: 'sso-access-1', refreshToken: 'sso-refresh-1' })+ expect(fakes.logLines.join('\n')).toMatch(/harness session not made/)+ })+})++describe('moving a signed-in CLI over, silently', () => {+ it('a session from before the upgrade stays signed in: its next renewal turns it into a Harness session', async () => {+ // Today's CLI: signed in through SSO, holding SSO tokens.+ const before = await signIn()+ expect(await me(before.data.token)).toBe(200)++ // The upgraded CLI renews as it always does, asking for a Harness session.+ const moved = await refresh(before.data.refreshToken, { harnessSession: ASK_COMPUTER })+ expect(moved.status).toBe(200)+ expect(moved.body.data!.token).toMatch(/^hna_/)+ expect(moved.body.data!.refreshToken).toMatch(/^hnr_/)+ expect(moved.body.data!.harnessSession).toBe(true)+ // The server holds the SSO refresh token the renewal rotated to; the client never sees it.+ expect(decryptMachineCredential(String(fakes.sessions[0]!.ssoRefresh))).toBe('sso-refresh-2-r')+ expect(JSON.stringify(moved.body)).not.toMatch(/sso-/)++ expect(await me(moved.body.data!.token)).toBe(200)+ const again = await refresh(moved.body.data!.refreshToken)+ expect(again.status).toBe(200)+ })++ it('an old CLI that asks for nothing renews its SSO tokens exactly as before', async () => {+ const before = await signIn()+ const renewed = await refresh(before.data.refreshToken)+ expect(renewed.status).toBe(200)+ expect(renewed.body.data).toMatchObject({ token: 'sso-access-2', refreshToken: 'sso-refresh-2-r' })+ expect(fakes.sessions).toHaveLength(0)+ })++ it('when the session cannot be made, hands back the renewed SSO tokens rather than losing the rotated one', async () => {+ const before = await signIn()+ fakes.setFailCreate(true)+ const renewed = await refresh(before.data.refreshToken, { harnessSession: ASK_COMPUTER })+ expect(renewed.status).toBe(200)+ expect(renewed.body.data).toMatchObject({ token: 'sso-access-2', refreshToken: 'sso-refresh-2-r' })+ // And that SSO sign-in still works.+ expect(await me(renewed.body.data!.token)).toBe(200)+ })+})++describe('the hourly SSO re-check', () => {+ async function harnessSignIn() {+ const { data } = await signIn(ASK_COMPUTER)+ return { token: String(data.token), refreshToken: String(data.refreshToken) }+ }++ it('asks SSO at most once an hour, saving the refresh token it rotates to', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { refreshToken } = await harnessSignIn()+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS - 60_000)+ expect((await refresh(refreshToken)).status).toBe(200)+ expect(fakes.sso.calls).toBe(0)++ vi.setSystemTime(Date.now() + 2 * 60_000)+ expect((await refresh(refreshToken)).status).toBe(200)+ expect(fakes.sso.calls).toBe(1)+ const row = fakes.sessions[0]!+ expect(decryptMachineCredential(String(row.ssoRefresh))).toBe('sso-refresh-2-r')+ expect((row.ssoCheckedAt as Date).getTime()).toBe(Date.now())+ expect(row.ssoRenewingAt ?? null).toBeNull()+ })++ it('keeps the refresh token when SSO does not rotate it', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ fakes.sso.rotate = false+ const { refreshToken } = await harnessSignIn()+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ expect((await refresh(refreshToken)).status).toBe(200)+ expect(decryptMachineCredential(String(fakes.sessions[0]!.ssoRefresh))).toBe('sso-refresh-1')+ })++ it('signing out of SSO (or a disabled account) ends the session within two hours, access token included', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const start = Date.now()+ const { refreshToken } = await harnessSignIn()+ // The last access token issued before the next check.+ vi.setSystemTime(start + SSO_RECHECK_MS - 1)+ const last = String((await refresh(refreshToken)).body.data!.token)+ // The person signs out of Autonomous, or the account is disabled: its refresh tokens stop working.+ fakes.sso.live.clear()++ vi.setSystemTime(start + SSO_RECHECK_MS + 1)+ const refused = await refresh(refreshToken)+ expect(refused.status).toBe(401)+ expect(refused.body.error?.code).toBe('REFRESH_TOKEN_INVALID')+ // At once, not when that access token runs out.+ expect(await me(last)).toBe(401)+ // The stored SSO tokens are gone with it.+ const row = fakes.sessions[0]!+ expect(row.revokedAt).toBeInstanceOf(Date)+ expect(row.ssoRefresh ?? null).toBeNull()+ expect(row.ssoAccess ?? null).toBeNull()+ expect(Date.now() - start).toBeLessThan(2 * HOUR)+ })++ it('SSO being down keeps people signed in, for seven days from the last good check', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const start = Date.now()+ const { refreshToken } = await harnessSignIn()+ fakes.sso.down = true++ for (const at of [SSO_RECHECK_MS + 1, 3 * 24 * HOUR, SSO_OUTAGE_GRACE_MS - 60_000]) {+ vi.setSystemTime(start + at)+ const renewed = await refresh(refreshToken)+ expect(renewed.status).toBe(200)+ expect(await me(renewed.body.data!.token)).toBe(200)+ }+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()++ // Past the grace: its own answer, which clients show as "Sign in again" — and the session is kept, not ended.+ vi.setSystemTime(start + SSO_OUTAGE_GRACE_MS + 1)+ const late = await refresh(refreshToken)+ expect(late.status).toBe(403)+ expect(late.body.error?.code).toBe('SIGN_IN_AGAIN')+ expect(late.body.error?.message).toMatch(/sign in again/i)+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()++ // SSO back: the next renewal checks and carries on.+ fakes.sso.down = false+ const back = await refresh(refreshToken)+ expect(back.status).toBe(200)+ })++ it('a refusal after a renewal that never finished is not a sign-out', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const start = Date.now()+ const { refreshToken } = await harnessSignIn()+ // A renewal that reached SSO and was lost before its rotated token was saved (a pod died, Mongo failed): the+ // token the session holds is spent, and SSO refuses it — through no doing of the person.+ fakes.sessions[0]!.ssoRenewingAt = new Date(start)+ fakes.sso.live.clear()++ vi.setSystemTime(start + SSO_RECHECK_MS + 1)+ const renewed = await refresh(refreshToken)+ expect(renewed.status).toBe(200)+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()+ // Counted as unavailable: the grace still runs from the last good check, and then the person is asked to sign in+ // again rather than left retrying a token that will never work.+ vi.setSystemTime(start + SSO_OUTAGE_GRACE_MS + 1)+ const late = await refresh(refreshToken)+ expect(late.status).toBe(403)+ expect(late.body.error?.code).toBe('SIGN_IN_AGAIN')+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()+ })++ it('a renewal that fails leaves its mark, so a later refusal is not read as a sign-out', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const start = Date.now()+ const { refreshToken } = await harnessSignIn()+ fakes.sso.down = true+ vi.setSystemTime(start + SSO_RECHECK_MS + 1)+ expect((await refresh(refreshToken)).status).toBe(200)+ expect(fakes.sessions[0]!.ssoRenewingAt).toBeInstanceOf(Date)++ // The failed call may have rotated the token before it failed: a refusal now is ambiguous.+ fakes.sso.down = false+ fakes.sso.live.clear()+ vi.setSystemTime(start + 2 * SSO_RECHECK_MS + 2)+ expect((await refresh(refreshToken)).status).toBe(200)+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()+ })++ it('two renewals at once ask SSO once: the second neither waits nor burns the token', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { refreshToken } = await harnessSignIn()+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ let open!: () => void+ fakes.sso.gate = new Promise<void>((resolve) => { open = resolve })+ const first = refresh(refreshToken)+ await vi.waitFor(() => expect(fakes.sso.calls).toBe(1))+ // The first is still waiting on SSO: the second goes on without asking, on the grace.+ const second = await refresh(refreshToken)+ expect(second.status).toBe(200)+ expect(fakes.sso.calls).toBe(1)+ open()+ expect((await first).status).toBe(200)+ expect(fakes.sso.calls).toBe(1)+ expect(decryptMachineCredential(String(fakes.sessions[0]!.ssoRefresh))).toBe('sso-refresh-2-r')+ // The lock is released once the renewal is saved.+ expect([...fakes.redis.keys()].some((k) => k.startsWith('hnauth:ssorenew:'))).toBe(false)+ })++ it('an SSO answer for another account is not this session: counted as unavailable, not as a sign-out', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { refreshToken } = await harnessSignIn()+ fakes.users.set('u2', { id: 'u2', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })+ for (const [token] of fakes.sso.live) fakes.sso.live.set(token, '[email protected]')+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ expect((await refresh(refreshToken)).status).toBe(200)+ const row = fakes.sessions[0]!+ expect(row.revokedAt ?? null).toBeNull()+ // Nothing of the other account's sign-in is kept on this person's session.+ expect(decryptMachineCredential(String(row.ssoRefresh))).toBe('sso-refresh-1')+ expect(row.ssoRenewingAt).toBeInstanceOf(Date)+ })++ it('a renewal SSO answers but whose identity cannot be read keeps the rotated refresh token, never its access token, and is no check', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const start = Date.now()+ const { refreshToken } = await harnessSignIn()+ // The token endpoint answers; the profile service does not.+ vi.mocked(globalThis.fetch).mockImplementation(async () => new Response('', { status: 502 }))+ vi.setSystemTime(start + SSO_RECHECK_MS + 1)+ expect((await refresh(refreshToken)).status).toBe(200)+ const row = fakes.sessions[0]!+ expect(decryptMachineCredential(String(row.ssoRefresh))).toBe('sso-refresh-2-r')+ expect(row.ssoRenewingAt ?? null).toBeNull()+ expect((row.ssoCheckedAt as Date).getTime()).toBe(start)+ // The unverified access token is not kept: nothing can hand it on (billing).+ expect(row.ssoAccess ?? null).toBeNull()+ expect(row.ssoAccessExpiresAt ?? null).toBeNull()+ })++ it('a renewal SSO answers after the session was signed out writes nothing back onto it', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { refreshToken } = await harnessSignIn()+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ let open!: () => void+ fakes.sso.gate = new Promise<void>((resolve) => { open = resolve })+ const renewing = refresh(refreshToken)+ await vi.waitFor(() => expect(fakes.sso.calls).toBe(1))+ // Signed out while SSO is still answering the renewal.+ await revokeHarnessSession(refreshToken)+ open()+ expect((await renewing).status).toBe(401)+ const row = fakes.sessions[0]!+ expect(row.revokedAt).toBeInstanceOf(Date)+ expect(row.ssoRefresh ?? null).toBeNull()+ expect(row.ssoAccess ?? null).toBeNull()+ expect(row.ssoRenewingAt ?? null).toBeNull()+ })++ it('a session from the phone QR is never re-checked: it has no SSO sign-in behind it', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { data } = await signIn(ASK_COMPUTER)+ delete fakes.sessions[0]!.ssoRefresh+ vi.setSystemTime(Date.now() + 30 * 24 * HOUR)+ expect(await refreshHarnessSession(String(data.refreshToken))).toMatchObject({ expiresIn: 3600 })+ expect(fakes.sso.calls).toBe(0)+ })+})++describe('signing out', () => {+ it('ends the session and deletes the stored SSO tokens', async () => {+ const { data } = await signIn(ASK_COMPUTER)+ const res = await app.inject({ method: 'POST', url: '/api/auth/revoke', payload: { refreshToken: data.refreshToken } })+ expect(res.statusCode).toBe(200)+ expect(await me(data.token)).toBe(401)+ expect((await refresh(data.refreshToken)).status).toBe(401)+ const row = fakes.sessions[0]!+ expect(row.ssoRefresh ?? null).toBeNull()+ expect(row.ssoAccess ?? null).toBeNull()+ })++ it('removing the device ends it the same way', async () => {+ const { data } = await signIn(ASK_COMPUTER)+ const { revokeHarnessSessionById } = await import('./harnessSession.js')+ await revokeHarnessSessionById(fakes.sessions[0]!.id, USER.id)+ expect(await me(data.token)).toBe(401)+ expect(fakes.sessions[0]!.ssoRefresh ?? null).toBeNull()+ })++ it('a session naming no computer cannot turn one into a team machine without its machine key', async () => {+ const { data } = await signIn(ASK_COMPUTER)+ const res = await app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization: `Bearer ${String(data.token)}` },+ payload: { kind: 'team', computerId: 'a1b2c3d4e5f60718' } })+ expect(res.statusCode).toBe(403)+ expect(res.json().error.code).toBe('HANDOFF_NOT_ALLOWED')+ })+})++describe('billing, which still needs an SSO access token', () => {+ it('is given the stored one while it lasts, and a renewed one after', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ await signIn(ASK_COMPUTER)+ const id = fakes.sessions[0]!.id+ expect(await ssoAccessTokenFor(id, USER.id)).toBe('sso-access-1')+ expect(fakes.sso.calls).toBe(0)+ vi.setSystemTime(Date.now() + 2 * HOUR)+ expect(await ssoAccessTokenFor(id, USER.id)).toBe('sso-access-2')+ expect(fakes.sso.calls).toBe(1)+ expect(decryptMachineCredential(String(fakes.sessions[0]!.ssoRefresh))).toBe('sso-refresh-2-r')+ })++ it('is given nothing for another account’s session, an ended one, or a QR sign-in', async () => {+ const { data } = await signIn(ASK_COMPUTER)+ const id = fakes.sessions[0]!.id+ expect(await ssoAccessTokenFor(id, 'someone-else')).toBeNull()+ await revokeHarnessSession(String(data.refreshToken))+ expect(await ssoAccessTokenFor(id, USER.id)).toBeNull()+ expect(await ssoAccessTokenFor('nope', USER.id)).toBeNull()+ })++ it('never hands on an access token whose identity was not confirmed', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ await signIn(ASK_COMPUTER)+ const id = fakes.sessions[0]!.id+ vi.mocked(globalThis.fetch).mockImplementation(async () => new Response('', { status: 502 }))+ vi.setSystemTime(Date.now() + 2 * HOUR)+ // SSO renews it, the profile service cannot say whose it is: not handed on, now or on the next call.+ await expect(ssoAccessTokenFor(id, USER.id)).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })+ await expect(ssoAccessTokenFor(id, USER.id)).rejects.toMatchObject({ code: 'AUTH_SERVICE_UNAVAILABLE' })+ expect(fakes.sessions[0]!.ssoAccess ?? null).toBeNull()+ // Once it can be confirmed, billing gets one: the one SSO just gave.+ stubProfileService()+ expect(await ssoAccessTokenFor(id, USER.id)).toBe(`sso-access-${fakes.sso.counter}`)+ })++ it('two billing calls at its expiry both get the renewed token: the second waits for the first', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ await signIn(ASK_COMPUTER)+ const id = fakes.sessions[0]!.id+ vi.setSystemTime(Date.now() + 2 * HOUR)+ let open!: () => void+ fakes.sso.gate = new Promise<void>((resolve) => { open = resolve })+ const first = ssoAccessTokenFor(id, USER.id)+ await vi.waitFor(() => expect(fakes.sso.calls).toBe(1))+ const second = ssoAccessTokenFor(id, USER.id)+ open()+ expect(await first).toBe('sso-access-2')+ expect(await second).toBe('sso-access-2')+ expect(fakes.sso.calls).toBe(1)+ })++ it('says unavailable, not signed out, when SSO cannot renew it', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ await signIn(ASK_COMPUTER)+ fakes.sso.down = true+ vi.setSystemTime(Date.now() + 2 * HOUR)+ await expect(ssoAccessTokenFor(fakes.sessions[0]!.id, USER.id)).rejects.toBeInstanceOf(SsoAuthError)+ expect(fakes.sessions[0]!.revokedAt ?? null).toBeNull()+ })+})++describe('old sessions', () => {+ it('an ended session expires at once, so the expiry index deletes it 30 days on, like one that ran out idle', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const { data } = await signIn(ASK_COMPUTER)+ expect((fakes.sessions[0]!.expiresAt as Date).getTime()).toBeGreaterThan(Date.now() + 89 * 24 * HOUR)+ await revokeHarnessSession(String(data.refreshToken))+ expect((fakes.sessions[0]!.expiresAt as Date).getTime()).toBe(Date.now())++ // MongoDB's own expiry: a row goes 30 days after its `expiresAt`.+ const runCommandRaw = vi.fn(async () => ({ ok: 1 }))+ await ensureHarnessSessionExpiry({ $runCommandRaw: runCommandRaw } as never)+ expect(runCommandRaw).toHaveBeenCalledWith({ createIndexes: 'harness_sessions', indexes: [+ { key: { expiresAt: 1 }, name: 'harness_session_expiry', expireAfterSeconds: 30 * 24 * 60 * 60 },+ ] })+ })+})++describe('no token is ever logged', () => {+ it('across sign-in, move-over, renewal, outage, refusal and sign-out', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ const seen: string[] = []+ const keep = (data: Record<string, unknown> | undefined) => {+ for (const v of [data?.token, data?.refreshToken]) if (typeof v === 'string') seen.push(v)+ }+ const a = await signIn(ASK_COMPUTER); keep(a.data)+ const b = await signIn(); keep(b.data)+ const moved = await refresh(b.data.refreshToken, { harnessSession: ASK_COMPUTER }); keep(moved.body.data)+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ keep((await refresh(a.data.refreshToken)).body.data)+ fakes.sso.down = true+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ keep((await refresh(moved.body.data!.refreshToken)).body.data)+ fakes.sso.down = false+ fakes.sso.live.clear()+ vi.setSystemTime(Date.now() + SSO_RECHECK_MS + 1)+ await refresh(a.data.refreshToken)+ await app.inject({ method: 'POST', url: '/api/auth/revoke', payload: { refreshToken: moved.body.data!.refreshToken } })+ fakes.setFailCreate(true)+ keep((await signIn(ASK_COMPUTER)).data)++ // Every SSO token the fake service issued, and every Harness token handed out.+ for (let i = 1; i <= fakes.sso.counter; i++) seen.push(`sso-access-${i}`, `sso-refresh-${i}`)+ for (const row of fakes.sessions) if (typeof row.ssoRefresh === 'string') seen.push(row.ssoRefresh)+ expect(seen.filter((t) => t.startsWith('hna_')).length).toBeGreaterThan(2)+ expect(fakes.logLines.length).toBeGreaterThan(0)+ const logs = fakes.logLines.join('\n')+ for (const token of seen) expect(logs).not.toContain(token)+ })+})diff --git a/backend/src/lib/ssoSession.ts b/backend/src/lib/ssoSession.tsnew file mode 100644index 000000000..9a333c3ac--- /dev/null+++ b/backend/src/lib/ssoSession.ts@@ -0,0 +1,245 @@+import { randomBytes } from 'node:crypto'+import type { HarnessSession, Prisma, PrismaClient } from '@prisma/client'+import { pub } from './bus.js'+import { prisma } from './prisma.js'+import { decryptMachineCredential, encryptMachineCredential } from './machineCredential.js'+import { normalizeSsoClientId, refreshAccessToken, SsoTokenError, type SsoClientId } from './sso.js'+import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'+import { storedAutonomousEnvironment, type AutonomousEnvironment } from './autonomousEnvironment.js'+import { logger } from '../utils/logger.js'++/**+ * Harness sessions an SSO sign-in backs: the CLI and Desktop sign in through Autonomous SSO once, then hold a session of+ * Harness's own (lib/harnessSession.ts), so an ordinary request never waits on the account service.+ *+ * CLI → POST /api/auth/exchange { …, harnessSession: { kind, label } } → { token: hna_…, refreshToken: hnr_…, harnessSession: true }+ * CLI → POST /api/auth/refresh { refreshToken: <SSO>, harnessSession } → the same: today's sign-ins move over on renewal+ * CLI → POST /api/auth/refresh { refreshToken: hnr_… } → a new access token, re-checked with SSO hourly+ *+ * The person's SSO refresh token stays here, encrypted on the session (lib/machineCredential.ts), and is never handed to+ * a client again. Every renewal of the session re-checks it with SSO at most once an hour ([SSO_RECHECK_MS]):+ *+ * - SSO renews it: the rotated refresh token is saved, and the session goes on.+ * - SSO refuses it, and the token held is the one the last renewal saved: the person signed out of Autonomous or the+ * account was disabled. The session ends, and its stored tokens with it.+ * - Anything else — SSO slow, down, failing, answering for another account, or refusing a token after a renewal that+ * never finished — is SSO UNAVAILABLE, never a sign-out: the session goes on for [SSO_OUTAGE_GRACE_MS] from its last+ * good check. After that its renewals answer `SIGN_IN_AGAIN`, which a client shows as "Sign in again": the session+ * is not ended (SSO coming back renews it), but nobody is left retrying a sign-in that may never work again.+ *+ * Every write a renewal makes is on a session still live: one signed out while SSO was answering gets nothing back.+ * An access token is kept only once SSO's profile service has confirmed whose it is, so billing never forwards one+ * that was not.+ *+ * Two renewals of one session never ask SSO at once: a renewal takes the session's lock in Redis, and one that finds it+ * taken goes on without asking. Before asking, a renewal marks the session (`ssoRenewingAt`); only saving SSO's answer+ * clears the mark. A mark left behind means a rotated refresh token may have been lost on the way (a pod died, the save+ * failed, the request timed out after SSO answered), and so a refusal of the stored token proves nothing.+ *+ * A session made here names no computer, even for a computer: naming one is what lets a sign-in turn that computer into a+ * team machine without its machine key (routes/auth.ts `isThisComputer`), and an SSO sign-in has never had that power.+ */++export const SSO_RECHECK_MS = 60 * 60_000+export const SSO_OUTAGE_GRACE_MS = 7 * 24 * 60 * 60_000+/** How long ended and idle-expired sessions are kept before their expiry index deletes them ([ensureHarnessSessionExpiry]). */+export const ENDED_SESSION_KEEP_MS = 30 * 24 * 60 * 60_000+/** Longer than a renewal can take (two SSO calls, each bounded by `SSO_PROFILE_TIMEOUT_MS`). */+const RENEW_LOCK_SEC = 60+/** An access token kept for billing is renewed this long before it runs out. */+const ACCESS_SKEW_MS = 60_000++const lockKey = (sessionId: string): string => `hnauth:ssorenew:${sessionId}`+/** How long billing waits for another renewal of the same session to finish before it says unavailable. */+const BUSY_WAIT_MS = RENEW_LOCK_SEC * 1000+const BUSY_POLL_MS = 100+// Not yet revoked. On MongoDB `revokedAt: null` alone does not match a field that is absent (lib/harnessSession.ts).+const notRevoked: Prisma.HarnessSessionWhereInput = { OR: [{ revokedAt: null }, { revokedAt: { isSet: false } }] }+// Delete the lock only if it is still this renewal's: one that outlived its lock must not release the next one's.+const RELEASE_SCRIPT = `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0`++export type SsoSessionKind = 'computer' | 'viewer'+export interface SsoSessionRequest { kind: SsoSessionKind; label: string }++/**+ * What a sign-in or renewal asks for in `harnessSession`: undefined when it asks for nothing (an older client, which+ * keeps its SSO tokens), null when it asks for something that is not a computer's or a viewer's session.+ */+export function parseSsoSessionRequest(raw: unknown): SsoSessionRequest | null | undefined {+ if (raw === undefined || raw === null) return undefined+ if (typeof raw !== 'object' || Array.isArray(raw)) return null+ const { kind, label } = raw as { kind?: unknown; label?: unknown }+ if (kind !== 'computer' && kind !== 'viewer') return null+ if (label !== undefined && typeof label !== 'string') return null+ const named = (label ?? '').trim().slice(0, 80)+ return { kind, label: named || (kind === 'computer' ? 'Computer' : 'Desktop') }+}++/** An SSO sign-in's tokens, as the token endpoint gave them. */+export interface SsoGrant { accessToken: string; refreshToken: string; expiresIn?: number }++const accessExpiry = (expiresIn: number | undefined, now: number): Date | null =>+ typeof expiresIn === 'number' && expiresIn > 0 ? new Date(now + expiresIn * 1000) : null++/** The fields a new session keeps for its SSO sign-in. Throws when they cannot be encrypted (no credential key). */+export function ssoSessionData(grant: SsoGrant, autonomousEnv: AutonomousEnvironment, clientId: SsoClientId | undefined, now = Date.now()) {+ return {+ ssoRefresh: encryptMachineCredential(grant.refreshToken),+ ssoAccess: encryptMachineCredential(grant.accessToken),+ ssoAccessExpiresAt: accessExpiry(grant.expiresIn, now),+ ssoEnv: autonomousEnv,+ ...(clientId ? { ssoClientId: clientId } : {}),+ ssoCheckedAt: new Date(now),+ }+}++/** A session ending: it is revoked, the SSO tokens it held are deleted with it, and it expires now — so the expiry+ * index deletes the row [ENDED_SESSION_KEEP_MS] later ([ensureHarnessSessionExpiry]). */+export function endedSessionData(now = new Date()) {+ return { revokedAt: now, expiresAt: now, ssoRefresh: null, ssoAccess: null, ssoAccessExpiresAt: null, ssoRenewingAt: null }+}++type Renewal =+ | { outcome: 'renewed'; accessToken: string }+ /** Another renewal saved a good answer meanwhile: [row] is the session as it left it. */+ | { outcome: 'fresh'; row: HarnessSession }+ | { outcome: 'ended' }+ | { outcome: 'busy' }+ | { outcome: 'unavailable' }++const unavailable = (): SsoAuthError =>+ new SsoAuthError('The sign-in service is unavailable; retrying', 'AUTH_SERVICE_UNAVAILABLE')++/** A renewal past the outage grace: shown to the person as "Sign in again" (lib/ssoSession.ts, above). */+export const ssoSignInAgainError = (): SsoAuthError =>+ new SsoAuthError('Sign in again: this sign-in could not be confirmed with your Autonomous account for 7 days', 'SIGN_IN_AGAIN')++/** Write [data] on session [sessionId] only while it is live. False when it ended meanwhile: nothing was written. */+async function writeLive(sessionId: string, data: Prisma.HarnessSessionUpdateManyMutationInput): Promise<boolean> {+ const { count } = await prisma.harnessSession.updateMany({ where: { id: sessionId, ...notRevoked }, data })+ return count > 0+}++/** Why a renewal could not get an answer, for the log: an error's kind, never its text (which could quote a request). */+const reasonOf = (err: unknown): string =>+ err instanceof SsoTokenError || err instanceof SsoAuthError ? err.code : err instanceof Error ? err.name : 'unknown'++/**+ * Ask SSO to renew session [sessionId]'s sign-in, once, under its lock — unless [fresh] says the session, read again+ * under the lock, no longer needs it.+ */+async function renew(sessionId: string, fresh: (row: HarnessSession, now: number) => boolean): Promise<Renewal> {+ const owner = randomBytes(16).toString('hex')+ if (await pub.set(lockKey(sessionId), owner, 'EX', RENEW_LOCK_SEC, 'NX') !== 'OK') return { outcome: 'busy' }+ try {+ const row = await prisma.harnessSession.findUnique({ where: { id: sessionId } })+ if (!row || row.revokedAt) return { outcome: 'ended' }+ if (!row.ssoRefresh) return { outcome: 'unavailable' }+ const now = Date.now()+ if (fresh(row, now)) return { outcome: 'fresh', row }++ const unfinished = row.ssoRenewingAt instanceof Date+ if (!unfinished && !(await writeLive(sessionId, { ssoRenewingAt: new Date(now) }))) return { outcome: 'ended' }+ const held = decryptMachineCredential(row.ssoRefresh)+ const autonomousEnv = storedAutonomousEnvironment(row.ssoEnv)+ let tokens: Awaited<ReturnType<typeof refreshAccessToken>>+ try {+ tokens = await refreshAccessToken(held, autonomousEnv, normalizeSsoClientId(row.ssoClientId))+ } catch (err) {+ if (err instanceof SsoTokenError && err.code === 'INVALID_GRANT' && !unfinished) {+ await writeLive(sessionId, endedSessionData())+ logger.info('sso sign-in ended a harness session', { sessionId, userId: row.userId })+ return { outcome: 'ended' }+ }+ logger.warn('sso re-check unavailable', { sessionId, userId: row.userId, reason: reasonOf(err), unfinished })+ return { outcome: 'unavailable' }+ }+ const accessToken = tokens.access_token+ const refreshToken = tokens.refresh_token || held+ if (!accessToken) {+ logger.warn('sso re-check unavailable', { sessionId, userId: row.userId, reason: 'NO_ACCESS_TOKEN', unfinished })+ return { outcome: 'unavailable' }+ }+ // The renewed sign-in must still be this session's person. Not reachable is unavailable, and so is someone else:+ // nothing here says this person signed out, and their session is not handed to the other account either.+ let identity: Awaited<ReturnType<typeof authenticateAccessToken>> | null = null+ try { identity = await authenticateAccessToken(accessToken, autonomousEnv, { allowHarnessSession: false }) } catch (err) {+ logger.warn('sso re-check unavailable', { sessionId, userId: row.userId, reason: reasonOf(err), unfinished })+ }+ if (identity && identity.sub !== row.userId) {+ logger.warn('sso re-check answered for another account', { sessionId, userId: row.userId })+ return { outcome: 'unavailable' }+ }+ // Saved in one write, which also clears the mark — on a session still live: one signed out while SSO answered keeps+ // nothing. Unidentified, the rotated refresh token is still kept (losing it would lose the sign-in), but its access+ // token is not, and the session is not counted as checked.+ const saved = await writeLive(sessionId, {+ ssoRefresh: encryptMachineCredential(refreshToken),+ ssoAccess: identity ? encryptMachineCredential(accessToken) : null,+ ssoAccessExpiresAt: identity ? accessExpiry(tokens.expires_in, now) : null,+ ssoRenewingAt: null,+ ...(identity ? { ssoCheckedAt: new Date(now) } : {}),+ })+ if (!saved) return { outcome: 'ended' }+ return identity ? { outcome: 'renewed', accessToken } : { outcome: 'unavailable' }+ } catch (err) {+ // Redis, Mongo or the credential key failing: a mark already written stays.+ logger.warn('sso re-check unavailable', { sessionId, reason: reasonOf(err) })+ return { outcome: 'unavailable' }+ } finally {+ await pub.eval(RELEASE_SCRIPT, 1, lockKey(sessionId), owner).catch(() => { /* it runs out on its own */ })+ }+}++/**+ * Whether session [session] may renew, as far as its SSO sign-in goes: `ok`, `ended` (it ended: the caller's 401), or+ * `sign-in-again` (SSO has not confirmed the sign-in within the grace: [ssoSignInAgainError]). A session no SSO sign-in+ * backs is always `ok`.+ */+export async function recheckSsoSession(session: HarnessSession): Promise<'ok' | 'ended' | 'sign-in-again'> {+ if (!session.ssoRefresh) return 'ok'+ const checkedAt = session.ssoCheckedAt?.getTime() ?? 0+ const recent = (row: HarnessSession, now: number): boolean => now - (row.ssoCheckedAt?.getTime() ?? 0) < SSO_RECHECK_MS+ if (recent(session, Date.now())) return 'ok'+ let renewal: Renewal+ try { renewal = await renew(session.id, recent) } catch (err) {+ logger.warn('sso re-check unavailable', { sessionId: session.id, reason: reasonOf(err) })+ renewal = { outcome: 'unavailable' }+ }+ if (renewal.outcome === 'ended') return 'ended'+ if (renewal.outcome === 'renewed' || renewal.outcome === 'fresh') return 'ok'+ return Date.now() - checkedAt < SSO_OUTAGE_GRACE_MS ? 'ok' : 'sign-in-again'+}++/**+ * An SSO access token for session [sessionId] of [userId], for the routes that forward one to the account service+ * (billing, lib/autonomousBff.ts). Null when the session is not that person's, has ended, or has no SSO sign-in+ * behind it (a QR or handoff session). Throws `AUTH_SERVICE_UNAVAILABLE` when SSO cannot give one now. Only a token+ * whose identity SSO confirmed is ever kept, so only such a token is ever handed on. A call that finds another renewal+ * of the session under way waits for it and reads its answer, rather than failing.+ */+export async function ssoAccessTokenFor(sessionId: string, userId: string): Promise<string | null> {+ const usable = (r: HarnessSession, now: number): boolean =>+ !!r.ssoAccess && r.ssoAccessExpiresAt instanceof Date && r.ssoAccessExpiresAt.getTime() > now + ACCESS_SKEW_MS+ const waitUntil = Date.now() + BUSY_WAIT_MS+ for (;;) {+ const row = await prisma.harnessSession.findUnique({ where: { id: sessionId } })+ if (!row || row.userId !== userId || row.revokedAt || !row.ssoRefresh) return null+ if (usable(row, Date.now())) return decryptMachineCredential(row.ssoAccess!)+ const renewal = await renew(sessionId, usable)+ if (renewal.outcome === 'renewed') return renewal.accessToken+ if (renewal.outcome === 'fresh') return decryptMachineCredential(renewal.row.ssoAccess!)+ if (renewal.outcome === 'ended') return null+ if (renewal.outcome === 'unavailable' || Date.now() >= waitUntil) throw unavailable()+ await new Promise((resolve) => setTimeout(resolve, BUSY_POLL_MS))+ }+}++/**+ * Sessions are deleted [ENDED_SESSION_KEEP_MS] after they expire: idle past their lifetime, or ended+ * ([endedSessionData] expires them). Nothing else deletes them. Run by the worker at start (worker.ts).+ */+export async function ensureHarnessSessionExpiry(db: Pick<PrismaClient, '$runCommandRaw'>): Promise<void> {+ await db.$runCommandRaw({ createIndexes: 'harness_sessions', indexes: [{ key: { expiresAt: 1 }, name: 'harness_session_expiry',+ expireAfterSeconds: ENDED_SESSION_KEEP_MS / 1000 }] })+}diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.tsindex 0dbeca248..0da7bd614 100644--- a/backend/src/routes/auth.ts+++ b/backend/src/routes/auth.ts@@ -24,7 +24,8 @@ import {} from '../lib/sso.js'import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'import { isHarnessRefreshToken } from '../lib/harnessTokenFormat.js'-import { redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff } from '../lib/harnessSession.js'+import { createSsoSession, redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff, type HarnessTokens } from '../lib/harnessSession.js'+import { parseSsoSessionRequest, type SsoGrant, type SsoSessionRequest } from '../lib/ssoSession.js'import { normalizeSignInAttribution, type SignInAttribution } from '../lib/signInAttribution.js'import { createHash } from 'node:crypto'import { ed25519 } from '@noble/curves/ed25519.js'@@ -80,6 +81,43 @@ async function teamHostMachine(user: AuthUser, named: string | undefined): Promireturn ordinary(machine) ? named : false}+/**+ * The Harness session a sign-in or renewal asked for (lib/ssoSession.ts), made from its SSO tokens. Null when it cannot+ * be made — no SSO refresh token to keep, the account gone, the store or credential key failing: the caller then answers+ * with the SSO tokens as before, so the person stays signed in either way, and a rotated SSO refresh token is never lost.+ */+async function harnessSessionFor(+ userId: string,+ asked: SsoSessionRequest,+ grant: Partial<SsoGrant>,+ autonomousEnv: AutonomousEnvironment,+ clientId: ReturnType<typeof normalizeSsoClientId>,+): Promise<HarnessTokens | null> {+ if (!grant.accessToken || !grant.refreshToken) {+ logger.warn('harness session not made; signed in with SSO tokens', { userId, reason: 'NO_SSO_REFRESH_TOKEN' })+ return null+ }+ try {+ const tokens = await createSsoSession(userId, asked, grant as SsoGrant, autonomousEnv, clientId)+ if (!tokens) logger.warn('harness session not made; signed in with SSO tokens', { userId, reason: 'NO_ACCOUNT' })+ return tokens+ } catch (e) {+ // The error's kind only: a store's message can quote what it was asked to write.+ logger.warn('harness session not made; signed in with SSO tokens', { userId, reason: e instanceof Error ? e.name : 'unknown' })+ return null+ }+}++/** A Harness session's tokens, as a sign-in or renewal hands them back in place of the SSO ones. */+const harnessSessionBody = (tokens: HarnessTokens) => ({+ token: tokens.token,+ refreshToken: tokens.refreshToken,+ expiresIn: tokens.expiresIn,+ kind: tokens.kind,+ autonomousEnv: tokens.autonomousEnv,+ harnessSession: true,+})+/** Reporting only: a sign-in whose attribution cannot be stored still signs in. */async function recordAttribution(userId: string, attribution: SignInAttribution): Promise<void> {try {@@ -120,11 +158,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {// then validates the access token through the profile service, mirrors the user and returns that// SAME access token in the body. No backend-owned session JWT is minted.// `attribution` is the `utm_*` + `rid` auth-service carried back onto the callback URL (lib/signInAttribution.ts).- app.post<{ Body: { code?: string; state?: string; tx?: string; attribution?: unknown } }>(+ // `harnessSession: { kind, label }` asks for a Harness session in place of the SSO tokens (lib/ssoSession.ts).+ app.post<{ Body: { code?: string; state?: string; tx?: string; attribution?: unknown; harnessSession?: unknown } }>('/api/auth/exchange',async (req, reply) => {const { code, state, tx: txRaw } = req.body ?? {}const attribution = normalizeSignInAttribution(req.body?.attribution)+ const asked = parseSsoSessionRequest(req.body?.harnessSession)+ if (asked === null) return sendError(reply, 'Ask for a computer or a viewer session', 'INVALID_HARNESS_SESSION', 400)let tx: SsoTx | null = nulltry {tx = txRaw ? await consumeTx(txRaw) : null@@ -153,6 +194,9 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {...(attribution ? { attribution } : {}),})if (attribution) await recordAttribution(user.sub, attribution)+ const session = asked && await harnessSessionFor(user.sub, asked,+ { accessToken: token, refreshToken: tokens.refresh_token, expiresIn: tokens.expires_in }, tx.autonomousEnv, tx.clientId)+ if (session) return sendSuccess(reply, { ...harnessSessionBody(session), next: tx.next })return sendSuccess(reply, {token,next: tx.next,@@ -184,7 +228,9 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {},)- app.post<{ Body: { refreshToken?: string; autonomousEnv?: AutonomousEnvironment; clientId?: string } }>(+ // An SSO renewal that asks for `harnessSession` is moved over to one (lib/ssoSession.ts): today's signed-in CLIs and+ // Desktops switch silently on their next renewal. A Harness refresh token ignores it.+ app.post<{ Body: { refreshToken?: string; autonomousEnv?: AutonomousEnvironment; clientId?: string; harnessSession?: unknown } }>('/api/auth/refresh',async (req, reply) => {const refreshToken = typeof req.body?.refreshToken === 'string' ? req.body.refreshToken.trim() : ''@@ -197,11 +243,17 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {if (!tokens) return sendError(reply, 'Refresh token is invalid or expired', 'REFRESH_TOKEN_INVALID', 401)return sendSuccess(reply, tokens)} catch (e) {+ // SSO not confirming the sign-in within its grace (lib/ssoSession.ts): its own answer, which clients show as+ // "Sign in again" and neither sign out over nor retry silently. Not a 401: the session is not over.+ if (e instanceof SsoAuthError && e.code === 'SIGN_IN_AGAIN') return sendError(reply, e.message, e.code, 403)logger.error('harness session refresh failed', e)return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)}}+ const asked = parseSsoSessionRequest(req.body?.harnessSession)+ if (asked === null) return sendError(reply, 'Ask for a computer or a viewer session', 'INVALID_HARNESS_SESSION', 400)+let autonomousEnv: AutonomousEnvironmenttry { autonomousEnv = parseAutonomousEnvironment(req.body?.autonomousEnv) } catch {return sendError(reply, 'invalid Autonomous environment', 'INVALID_AUTONOMOUS_ENV', 400)@@ -209,7 +261,8 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {try {// 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 clientId = normalizeSsoClientId(req.body?.clientId)+ const tokens = await refreshAccessToken(refreshToken, autonomousEnv, 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)@@ -219,6 +272,13 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {rotatedRefreshToken: !!tokens.refresh_token,expiresIn: tokens.expires_in,})+ // Whatever this answers, SSO may already have rotated the refresh token: the new one is handed back either way.+ const session = asked && await harnessSessionFor(user.sub, asked,+ { accessToken: token, refreshToken: tokens.refresh_token || refreshToken, expiresIn: tokens.expires_in }, autonomousEnv, clientId)+ if (session) {+ logger.info('sso sign-in moved to a harness session', { userId: user.sub, kind: session.kind })+ return sendSuccess(reply, harnessSessionBody(session))+ }return sendSuccess(reply, {token,...(tokens.refresh_token ? { refreshToken: tokens.refresh_token } : {}),diff --git a/backend/src/routes/machines.ts b/backend/src/routes/machines.tsindex cc3e58c16..b565ebca8 100644--- a/backend/src/routes/machines.ts+++ b/backend/src/routes/machines.ts@@ -7,7 +7,8 @@ import { validateBody, validateParams, validateQuery } from '../middlewares/valiimport { isMachineId } from '../utils/slug.js'import { sendSuccess, sendCreated, sendError } from '../utils/response.js'import { logger } from '../utils/logger.js'-import { bearerToken } from '../lib/ssoAuth.js'+import { bearerToken, SsoAuthError, type AuthUser } from '../lib/ssoAuth.js'+import { ssoAccessTokenFor } from '../lib/ssoSession.js'import { isHarnessAccessToken } from '../lib/harnessTokenFormat.js'import { AppError } from '../errors/index.js'import { requestedWebOrigin, resolveWebOrigin } from '../lib/sso.js'@@ -61,13 +62,22 @@ const billingCompleteBody = z.object({referenceCode: z.string().trim().min(1).max(128).optional(),})-function requestAccessToken(authorization: string | undefined): string {- const token = bearerToken(authorization)+async function requestAccessToken(req: { headers: { authorization?: string }; user?: AuthUser }): Promise<string> {+ const token = bearerToken(req.headers.authorization)if (!token) throw new Error('Authenticated request is missing its SSO access token')// Billing is the Autonomous account's own business, and the caller's token is forwarded there- // (lib/autonomousBff.ts). A session Harness issued itself — a phone, or a computer signed in by+ // (lib/autonomousBff.ts). A session an SSO sign-in backs forwards the one the backend keeps for it+ // (lib/ssoSession.ts). Any other 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)) {+ let kept: string | null = null+ try {+ kept = req.user?.harnessSessionId ? await ssoAccessTokenFor(req.user.harnessSessionId, req.user.sub) : null+ } catch (err) {+ if (err instanceof SsoAuthError) throw new AppError(err.message, 503, err.code)+ throw err+ }+ if (kept) return keptthrow 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@@ -169,7 +179,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {agent.machineId,userId,req.user!.email,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),requestWebOrigin(req),req.user!.autonomousEnv,)@@ -188,7 +198,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {req.params.machineId,req.user!.sub,req.user!.email,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),requestWebOrigin(req),req.user!.autonomousEnv,)@@ -206,7 +216,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {req.params.machineId,req.user!.sub,req.user!.email,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),requestWebOrigin(req),req.body.sessionId,req.body.referenceCode,@@ -226,7 +236,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {const billing = await machineBillingService.getBilling(req.params.machineId,req.user!.sub,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),req.user!.autonomousEnv,)return sendSuccess(reply, { billing })@@ -243,7 +253,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {req.user!.sub,req.body.planId,req.user!.email,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),requestWebOrigin(req),req.user!.autonomousEnv,)@@ -260,7 +270,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {const billing = await machineBillingService.complete(req.params.machineId,req.user!.sub,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),req.body.operationId,req.body.outcome,req.user!.autonomousEnv,@@ -276,7 +286,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {const billing = await machineBillingService.cancel(req.params.machineId,req.user!.sub,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),req.user!.autonomousEnv,)return sendSuccess(reply, { billing })@@ -290,7 +300,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {const billing = await machineBillingService.renew(req.params.machineId,req.user!.sub,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),req.user!.autonomousEnv,)return sendSuccess(reply, { billing })@@ -400,7 +410,7 @@ export async function machineRoutes(app: FastifyInstance): Promise<void> {await machineService.destroy(req.params.machineId,req.user!,- requestAccessToken(req.headers.authorization),+ await requestAccessToken(req),)return sendSuccess(reply, { deleted: true })},diff --git a/backend/src/routes/machinesBillingToken.test.ts b/backend/src/routes/machinesBillingToken.test.tsnew file mode 100644index 000000000..a4b855bbf--- /dev/null+++ b/backend/src/routes/machinesBillingToken.test.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'++// Billing and machine deletion forward the caller's SSO access token to the account service (lib/autonomousBff.ts).+// A Harness session an SSO sign-in backs (lib/ssoSession.ts) forwards the one the backend keeps for it; any other+// Harness session is told to sign in with Google or Apple, as before. ssoSession's own behaviour is tested in+// lib/ssoSession.test.ts: here only its answer is set.+const m = vi.hoisted(() => ({+ beginCheckout: vi.fn(async () => ({ redirectUrl: 'https://pay.example/x' })),+ destroy: vi.fn(async () => undefined),+ ssoAccessTokenFor: vi.fn(async (): Promise<string | null> => null),+}))+vi.mock('../services/index.js', () => ({+ machineService: { destroy: m.destroy },+ machineBillingService: { beginCheckout: m.beginCheckout },+ userService: { get: vi.fn() },+}))+vi.mock('../lib/prisma.js', () => ({ prisma: {}, machineAlive: {} }))+vi.mock('../lib/machineAccess.js', () => ({ machinesSharedWith: vi.fn(async () => []) }))+vi.mock('../lib/ssoSession.js', () => ({ ssoAccessTokenFor: m.ssoAccessTokenFor }))++import { machineRoutes } from './machines.js'+import { errorHandler } from '../middlewares/errorHandler.js'+import { SsoAuthError, type AuthUser } from '../lib/ssoAuth.js'+import { HARNESS_ACCESS_PREFIX, newHarnessToken } from '../lib/harnessTokenFormat.js'++const MACHINE = 'a'.repeat(32)+const SSO_USER: AuthUser = { sub: 'u1', email: '[email protected]', role: 'user', autonomousEnv: 'prod' }+const HARNESS_USER: AuthUser = { ...SSO_USER, harnessSessionId: 'sess-1', harnessSessionKind: 'computer' }++let app: FastifyInstance+let caller: AuthUser++beforeEach(async () => {+ vi.clearAllMocks()+ app = Fastify()+ app.setErrorHandler(errorHandler)+ // What the authentication middleware leaves on the request.+ app.addHook('preHandler', async (req) => { req.user = caller })+ await app.register(machineRoutes)+ await app.ready()+})++const checkout = (token: string) =>+ app.inject({ method: 'POST', url: `/api/machines/${MACHINE}/checkout`, headers: { authorization: `Bearer ${token}` } })++describe('the SSO token billing forwards', () => {+ it('is the caller’s own for an SSO sign-in', async () => {+ caller = SSO_USER+ expect((await checkout('sso-access')).statusCode).toBe(200)+ expect(m.beginCheckout).toHaveBeenCalledWith(MACHINE, 'u1', '[email protected]', 'sso-access', expect.any(String), 'prod')+ expect(m.ssoAccessTokenFor).not.toHaveBeenCalled()+ })++ it('is the one kept for a Harness session an SSO sign-in backs', async () => {+ caller = HARNESS_USER+ m.ssoAccessTokenFor.mockResolvedValueOnce('kept-sso-access')+ expect((await checkout(newHarnessToken(HARNESS_ACCESS_PREFIX))).statusCode).toBe(200)+ expect(m.ssoAccessTokenFor).toHaveBeenCalledWith('sess-1', 'u1')+ expect(m.beginCheckout).toHaveBeenCalledWith(MACHINE, 'u1', '[email protected]', 'kept-sso-access', expect.any(String), 'prod')+ })++ it('is none for a session nothing backs: sign in with Google or Apple, as before', async () => {+ caller = HARNESS_USER+ const res = await checkout(newHarnessToken(HARNESS_ACCESS_PREFIX))+ expect(res.statusCode).toBe(403)+ expect(res.json().error.code).toBe('NEEDS_AUTONOMOUS_SIGN_IN')+ expect(m.beginCheckout).not.toHaveBeenCalled()+ })++ it('is unavailable, not a sign-in prompt, when SSO cannot give one now', async () => {+ caller = HARNESS_USER+ m.ssoAccessTokenFor.mockRejectedValueOnce(new SsoAuthError('The sign-in service is unavailable; retrying', 'AUTH_SERVICE_UNAVAILABLE'))+ const res = await checkout(newHarnessToken(HARNESS_ACCESS_PREFIX))+ expect(res.statusCode).toBe(503)+ expect(res.json().error.code).toBe('AUTH_SERVICE_UNAVAILABLE')+ })++ it('reaches machine deletion the same way', async () => {+ caller = HARNESS_USER+ m.ssoAccessTokenFor.mockResolvedValueOnce('kept-sso-access')+ const res = await app.inject({ method: 'DELETE', url: `/api/machines/${MACHINE}`,+ headers: { authorization: `Bearer ${newHarnessToken(HARNESS_ACCESS_PREFIX)}` } })+ expect(res.statusCode).toBe(200)+ expect(m.destroy).toHaveBeenCalledWith(MACHINE, HARNESS_USER, 'kept-sso-access')+ })+})diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 14c341b36..6d076a73e 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -16,6 +16,7 @@ import {import { ensurePlans } from './lib/db/seed.js'import { prisma } from './lib/prisma.js'import { ensureProductUsageExpiry } from './lib/productUsage.js'+import { ensureHarnessSessionExpiry } from './lib/ssoSession.js'import { ensureTerminalExpiry } from './superTabs/terminal.js'import { ensureMentionExpiry } from './superTabs/mentions.js'import { ensurePartExpiry, startSwarmSweeps } from './superTabs/sweeps.js'@@ -40,6 +41,7 @@ async function start(): Promise<void> {await migrateUserPresencePerMachine()ensureSchema()await ensureProductUsageExpiry()+ await ensureHarnessSessionExpiry(prisma)await ensureTerminalExpiry(prisma)await ensureMentionExpiry(prisma)await ensurePartExpiry(prisma)diff --git a/cli/src/authCommand.spec.ts b/cli/src/authCommand.spec.tsindex 660b24a42..136d9525d 100644--- a/cli/src/authCommand.spec.ts+++ b/cli/src/authCommand.spec.ts@@ -823,3 +823,183 @@ describe('harness login --ticket', () => {expect(existsSync(join(root, 'auth', 'session.json'))).toBe(false)}, 30_000)})++// Ken (GO 10-28): people sign in through SSO once; after that this computer holds a Harness session (backend+// lib/ssoSession.ts), so an ordinary request never waits on the account service. Nobody signed in today is signed out.+describe('a Harness session in place of SSO tokens', () => {+ const HNA = `hna_${'a'.repeat(43)}`+ const HNR = `hnr_${'b'.repeat(43)}`+ const sessionOnDisk = (root: string): Record<string, unknown> => JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8'))+ // The sign-in's own calls: `auth status` may also ask other routes (the models list) on its own.+ const authCalls = (calls: Array<{ url: string; body: unknown }>) => calls.filter((c) => c.url.startsWith('/api/auth/'))+ // The backend's answer to a renewal: a Harness session when asked for one, the SSO tokens as before otherwise.+ const renewal = (body: any) => body.harnessSession+ ? { token: HNA, refreshToken: HNR, expiresIn: 3600, kind: 'computer', autonomousEnv: 'prod', harnessSession: true }+ : { token: 'tok_renewed', refreshToken: 'refresh_2', expiresIn: 3600 }++ it('a sign-in from before the upgrade stays signed in, and its next renewal moves it to a Harness session', async () => {+ const root = tempRoot()+ // Exactly what today's CLI writes after an SSO sign-in from the desktop app, its access token about to run out.+ seedSession(root, { expiresInMs: 30_000, overrides: { clientId: 'harness-desktop', signInEpoch: 'e1@1' } })+ const backend = await fakeBackend({ routes: { '/api/auth/refresh': renewal } })++ const result = await runAsync(root, ['auth', 'status', '--json'], backend.base)++ expect(result.status, result.stderr).toBe(0)+ expect(JSON.parse(result.stdout.trim())).toMatchObject({ loggedIn: true, machineId: 'm_seeded' })+ expect(authCalls(backend.calls)).toEqual([{ url: '/api/auth/refresh', body: {+ refreshToken: 'refresh_seeded', autonomousEnv: 'prod', clientId: 'harness-desktop',+ harnessSession: { kind: 'computer', label: expect.any(String) },+ } }])+ // The same sign-in, now holding the Harness session's tokens; nothing else about it changed.+ expect(sessionOnDisk(root)).toMatchObject({+ accessToken: HNA, refreshToken: HNR, computerId: 'a'.repeat(32), machineId: 'm_seeded', signInEpoch: 'e1@1',+ })+ expect(sessionOnDisk(root)).not.toHaveProperty('signedOut')+ // No token is printed.+ for (const token of [HNA, HNR, 'refresh_seeded', 'tok_seeded']) expect(result.stdout + result.stderr).not.toContain(token)+ })++ it('a Harness session renews as one, asking for nothing more; a QR or team sign-in never asks', async () => {+ for (const overrides of [{ refreshToken: HNR }, { method: 'qr', refreshToken: 'refresh_qr' }, { kind: 'team', refreshToken: `htr_${'c'.repeat(43)}` }]) {+ const root = tempRoot()+ seedSession(root, { expiresInMs: 30_000, overrides })+ const backend = await fakeBackend({ routes: { '/api/auth/refresh': renewal } })+ await runAsync(root, ['auth', 'status', '--json'], backend.base)+ expect(authCalls(backend.calls).map((c) => c.body)).toEqual([expect.not.objectContaining({ harnessSession: expect.anything() })])+ }+ }, 30_000)++ it('signing in asks for a Harness session for this computer, and keeps what the backend gave', async () => {+ const root = tempRoot()+ let redirectUri = ''+ let exchanged: any = null+ const { base } = await fakeBackend({+ authorizeNative: (body) => { redirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: (body) => { exchanged = body; return { token: HNA, refreshToken: HNR, expiresIn: 3600, kind: 'computer', autonomousEnv: 'prod', harnessSession: true } },+ resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ })+ const login = jsonChild(root, base, ['login', '--google', '--json'])+ expect(await login.next()).toMatchObject({ type: 'authorize_url' })+ await fetch(`${redirectUri}?code=code_123&state=state_456`)+ expect(await login.next()).toMatchObject({ type: 'result', status: 'success' })+ await login.exit+ expect(exchanged).toMatchObject({ code: 'code_123', harnessSession: { kind: 'computer', label: expect.any(String) } })+ expect(sessionOnDisk(root)).toMatchObject({ accessToken: HNA, refreshToken: HNR, machineId: 'm_new' })+ }, 30_000)++ it('signing out ends the Harness session on the server too', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { accessToken: HNA, refreshToken: HNR } })+ const backend = await fakeBackend({ routes: { '/api/auth/revoke': () => ({ revoked: true }) } })++ const result = await runAsync(root, ['logout', '--from-sign-out-button'], backend.base)++ expect(result.status, result.stderr).toBe(0)+ expect(authCalls(backend.calls)).toEqual([{ url: '/api/auth/revoke', body: { refreshToken: HNR } }])+ expect(existsSync(join(root, 'auth', 'session.json'))).toBe(false)+ expect(result.stdout + result.stderr).not.toContain(HNR)+ })++ it('signing out still signs out when the server cannot be reached, and says the server sign-out is pending', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { accessToken: HNA, refreshToken: HNR } })++ const result = await runAsync(root, ['logout', '--from-sign-out-button'], 'http://127.0.0.1:1')++ expect(result.status, result.stderr).toBe(0)+ expect(existsSync(join(root, 'auth', 'session.json'))).toBe(false)+ expect(result.stdout + result.stderr).toMatch(/could not end this sign-in on the server/i)+ expect(result.stdout + result.stderr).not.toContain(HNR)+ })++ it('a sign-in SSO has not confirmed for 7 days says "sign in again", and is kept, not signed out', async () => {+ const root = tempRoot()+ seedSession(root, { expiresInMs: 30_000, overrides: { accessToken: HNA, refreshToken: HNR } })+ const backend = await fakeBackend({ routes: {+ '/api/auth/refresh': () => new Refusal(403, 'SIGN_IN_AGAIN', 'Sign in again: this sign-in could not be confirmed with your Autonomous account for 7 days'),+ } })++ const json = await runAsync(root, ['auth', 'status', '--json'], backend.base)+ expect(JSON.parse(json.stdout.trim())).toMatchObject({ loggedIn: false, signedOut: 'sign-in-again' })+ // Kept as it was: not marked signed out, so SSO coming back renews it.+ expect(sessionOnDisk(root)).toMatchObject({ accessToken: HNA, refreshToken: HNR })+ expect(sessionOnDisk(root)).not.toHaveProperty('signedOut')++ const text = await runAsync(root, ['auth', 'status'], backend.base)+ expect(text.stdout).toMatch(/sign in again.*harness login/i)+ })++ it('recovers from "sign in again": harness login opens a fresh sign-in that replaces the stuck one', async () => {+ const root = tempRoot()+ // A Harness session SSO has not confirmed for 7 days: every renewal answers "sign in again".+ seedSession(root, { expiresInMs: 30_000, overrides: { accessToken: HNA, refreshToken: HNR } })+ const NEW_HNA = `hna_${'f'.repeat(43)}`+ const NEW_HNR = `hnr_${'g'.repeat(43)}`+ let redirectUri = ''+ const backend = await fakeBackend({+ authorizeNative: (body) => { redirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: () => ({ token: NEW_HNA, refreshToken: NEW_HNR, expiresIn: 3600, kind: 'computer', autonomousEnv: 'prod', harnessSession: true }),+ resolveComputer: () => ({ machine: { machineId: 'm_seeded' } }),+ routes: {+ '/api/auth/refresh': () => new Refusal(403, 'SIGN_IN_AGAIN', 'Sign in again'),+ '/api/auth/revoke': () => ({ revoked: true }),+ },+ })++ // What the message says to run: plain `harness login`, no flag.+ const login = jsonChild(root, backend.base, ['login', '--google', '--json'])+ expect(await login.next()).toMatchObject({ type: 'authorize_url' })+ await fetch(`${redirectUri}?code=code_123&state=state_456`)+ expect(await login.next()).toMatchObject({ type: 'result', status: 'success' })+ await login.exit++ // The stuck session is replaced, and ended on the server; the computer is signed in again.+ expect(sessionOnDisk(root)).toMatchObject({ accessToken: NEW_HNA, refreshToken: NEW_HNR })+ expect(authCalls(backend.calls).filter((c) => c.url === '/api/auth/revoke')).toEqual([{ url: '/api/auth/revoke', body: { refreshToken: HNR } }])+ const status = await runAsync(root, ['auth', 'status', '--json'], backend.base)+ expect(JSON.parse(status.stdout.trim())).toMatchObject({ loggedIn: true })+ }, 30_000)++ it('reset ends the Harness session on the server too', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { accessToken: HNA, refreshToken: HNR } })+ const backend = await fakeBackend({ routes: { '/api/auth/revoke': () => ({ revoked: true }) } })++ const result = await runAsync(root, ['reset', '--from-sign-out-button'], backend.base)++ expect(result.status, result.stderr).toBe(0)+ expect(authCalls(backend.calls)).toEqual([{ url: '/api/auth/revoke', body: { refreshToken: HNR } }])+ })++ it('login --force ends the previous Harness session once the new sign-in is in', async () => {+ const root = tempRoot()+ seedSession(root, { overrides: { accessToken: HNA, refreshToken: HNR } })+ const NEW_HNR = `hnr_${'d'.repeat(43)}`+ let redirectUri = ''+ const backend = await fakeBackend({+ authorizeNative: (body) => { redirectUri = body.redirectUri; return { authorizeUrl: 'https://sso.example.test/authorize?tx=abc', tx: 'tx_abc' } },+ exchange: () => ({ token: `hna_${'e'.repeat(43)}`, refreshToken: NEW_HNR, expiresIn: 3600, kind: 'computer', autonomousEnv: 'prod', harnessSession: true }),+ resolveComputer: () => ({ machine: { machineId: 'm_new' } }),+ routes: { '/api/auth/revoke': () => ({ revoked: true }) },+ })+ const login = jsonChild(root, backend.base, ['login', '--force', '--google', '--json'])+ expect(await login.next()).toMatchObject({ type: 'authorize_url' })+ await fetch(`${redirectUri}?code=code_123&state=state_456`)+ expect(await login.next()).toMatchObject({ type: 'result', status: 'success' })+ await login.exit+ expect(sessionOnDisk(root)).toMatchObject({ refreshToken: NEW_HNR })+ expect(authCalls(backend.calls).filter((c) => c.url === '/api/auth/revoke')).toEqual([{ url: '/api/auth/revoke', body: { refreshToken: HNR } }])+ }, 30_000)++ it('signing out of an SSO sign-in asks the server nothing, as before', async () => {+ const root = tempRoot()+ seedSession(root)+ const backend = await fakeBackend({ routes: { '/api/auth/revoke': () => ({ revoked: true }) } })++ const result = await runAsync(root, ['logout', '--from-sign-out-button'], backend.base)++ expect(result.status, result.stderr).toBe(0)+ expect(authCalls(backend.calls)).toEqual([])+ })+})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 840e8b623..3109791cd 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -49,7 +49,8 @@ import { infoBlockFooter } from './lib/infoBlockFooter.js'import { flashCommand } from './lib/flash.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE, type LoginCallbackParams } from './lib/loginCallback.js'import { ancestorsOnce, removeSignIn, SIGN_OUT_BUTTON_FLAG, signOutAsked, type Asker, type SignOutAsked } from './lib/signOut.js'-import { AUTH_DIR, AuthSessionError, AuthSessionManager, knownSsoClientId, newSignInEpoch, readAuthSession, readSignedOut, ssoClientIdFor, updateAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { AUTH_DIR, AuthSessionError, AuthSessionManager, harnessSessionRequest, knownSsoClientId, newSignInEpoch, readAuthSession, readSignedOut, ssoClientIdFor, updateAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'+import { revokeHarnessRefresh } from './team/handoff.js'import { handOffToGrid } from './lib/gridHandoff.js'import { claimTicket, qrSignIn, type QrSignInTokens } from './lib/qrSignIn.js'import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'@@ -350,9 +351,13 @@ async function authStatusCommand(json: boolean): Promise<void> {}let loggedIn = truelet offline = false+ let signInAgain = falsetry {await auth.accessToken()} catch (err) {+ // SSO has not confirmed this sign-in for its whole grace (backend lib/ssoSession.ts): kept, and the person asked to+ // sign in again.+ if (err instanceof AuthSessionError && err.code === 'SIGN_IN_AGAIN') signInAgain = true// Only a session the SSO service will never renew (or none at all) is "not signed in". A refresh// that could not be SERVED right now — no network, service down — is a signed-in computer that is// offline, and says so; it used to read as signed out and send the desktop app to a login screen@@ -363,7 +368,7 @@ async function authStatusCommand(json: boolean): Promise<void> {const latest = readAuthSession()const signedIn = loggedIn && latest !== nullconst fingerprintNow = thisDeviceFingerprint(false)- const waiting = signedIn ? null : signedOutWaiting()+ const waiting = signedIn ? null : signInAgain ? 'sign-in-again' : signedOutWaiting()const payload = {loggedIn: signedIn,...(waiting ? { signedOut: waiting } : {}),@@ -379,7 +384,9 @@ async function authStatusCommand(json: boolean): Promise<void> {...(fingerprintNow ? { fingerprint: fingerprintNow } : {}),}if (json) console.log(JSON.stringify(payload))- else {+ else if (signInAgain) {+ console.log('\n ✗ Sign in again: this computer\'s sign-in could not be confirmed with your Autonomous account for 7 days. Run: harness login\n')+ } else {console.log(`\n ${payload.loggedIn ? '✓ Signed in' : '✗ Not signed in'}${payload.machineId ? ` (machine ${payload.machineId})` : ''}${payload.loggedIn && payload.kind === 'team' ? ' — for team work only (harness team off undoes it)' : payload.loggedIn && payload.method === 'qr' ? ' — by your phone' : ''}\n`)// A session a phone approved is Harness's own, and billing's Autonomous service does not take it.// Say so where the person looks, not only when billing refuses. Grid is not named: it learns who@@ -538,20 +545,28 @@ async function loginCommand(// `/api/machines/resolve-computer` reached `onError`, which is JSON-unaware — so the ONE mode a// client drives answered a stack trace and NO result line at all, on the commonest path there// is (a computer that is already signed in).+ let stuck = falsetry {await resolveComputerMachine()} catch (err) {- // An `AuthSessionError` is passed on rather than coded here: it is not the backend failing, it- // is THIS computer's harness session, and only the caller knows which of the two sign-ins the- // person should be sent to. `harness login` is unaffected — it never caught this before either.- if (json && !(err instanceof AuthSessionError)) {- emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message })- process.exitCode = 1- return { signedIn: false }+ // A sign-in SSO has not confirmed for 7 days ("sign in again", backend lib/ssoSession.ts) is kept, but cannot be+ // renewed: signing in is what that message asks for, so this goes on to a fresh sign-in that replaces it, as+ // --force would. Without this, `harness login` retried the same refused renewal and never opened a sign-in.+ if (!(err instanceof AuthSessionError && err.code === 'SIGN_IN_AGAIN')) {+ // An `AuthSessionError` is passed on rather than coded here: it is not the backend failing, it+ // is THIS computer's harness session, and only the caller knows which of the two sign-ins the+ // person should be sent to. `harness login` is unaffected — it never caught this before either.+ if (json && !(err instanceof AuthSessionError)) {+ emit({ type: 'result', status: 'error', code: 'BACKEND_ERROR', message: (err as Error).message })+ process.exitCode = 1+ return { signedIn: false }+ }+ throw err}- throw err+ stuck = true}- return await succeed(true)+ if (!stuck) return await succeed(true)+ force = true}if (opts.method === 'ask') {const picked = await askSignInMethod()@@ -590,7 +605,10 @@ async function loginCommand(return { signedIn: false }}const stopped = stop !== null && stop.pid !== null+ const replaced = readAuthSession()?.refreshTokenconst outcome = await signIn()+ // The sign-in this one replaced ends on the server too, as `harness team on` ends the one it replaces.+ if (outcome.signedIn && replaced && readAuthSession()?.refreshToken !== replaced) await endSignInOnServer(replaced, 'the previous sign-in')// The daemon stopped for the switch comes back once it is made (`restartDaemonForIdentity`).return outcome.signedIn && stopped ? { ...outcome, stoppedDaemon: true } : outcome}, {@@ -834,6 +852,8 @@ async function browserSignIn(tx: start.tx,// The utm_* and rid auth.autonomous.ai carried back: how the account came (PR #785)....(callbackResult.attribution ? { attribution: callbackResult.attribution } : {}),+ // A Harness session in place of the SSO tokens (backend lib/ssoSession.ts); an older backend sends those.+ harnessSession: harnessSessionRequest(),})if (!exchanged.token) throw new Error('SSO exchange returned no access token')} catch (err) {@@ -1327,6 +1347,20 @@ async function updateCommand(force: boolean): Promise<void> {* It runs BEFORE the harness session is cleared, because `grid logout` tears down every serve child* on this box first, while the token that makes their deregistration authoritative still exists.*/+/** How long signing out waits for the server to end a Harness session. */+const SIGN_OUT_REVOKE_TIMEOUT_MS = 5_000++/**+ * End a Harness session ([refreshToken]) on the server: signing out, `reset`, and a `login --force` that replaced it.+ * An SSO sign-in is not ours to end. Best effort and bounded — never waits on, or fails over, the network — and says+ * so when the server could not be reached.+ */+async function endSignInOnServer(refreshToken: string | undefined, which = 'this sign-in'): Promise<void> {+ if (!/^(hnr|htr)_/.test(refreshToken ?? '')) return+ const ended = await revokeHarnessRefresh((path, body) => postJson(path, body, {}, AbortSignal.timeout(SIGN_OUT_REVOKE_TIMEOUT_MS)), refreshToken)+ if (!ended) console.log(`Could not end ${which} on the server; it can no longer be used from here, and ends on its own after 90 days unused.`)+}+async function logout(): Promise<void> {const chain = ancestorsOnce()const asked = personAsked('logout', chain)@@ -1336,7 +1370,10 @@ async function logout(): Promise<void> {// Before removeSignIn: see the note above on serve children. Its exit code is deliberately// dropped — this command cannot fail — and its own words have already reached the terminal.const gridOut = await passThroughToGridLogout([])+ const refreshToken = readAuthSession()?.refreshToken+ const endOnServer = endSignInOnServer(refreshToken)removeSignIn('logout', asked, chain)+ await endOnServerrmSync(MACHINE_NAME_FILE, { force: true })// Same reason as the name above: the cached machine list describes the account that just left, and the// local `/api/machines` fallback would otherwise hand it to whoever signs in next on this computer.@@ -1773,10 +1810,12 @@ async function resetCommand(): Promise<void> {const asked = personAsked('reset', chain)// Before anything is cleared: a pid file removed under a Harness still running leaves nothing able to stop it.const r = await stopDaemonOrExit()+ const refreshToken = readAuthSession()?.refreshTokenclearAdapterState()console.log(`\n ✓ Cleared local machine CLI state at ${tildify(env.ADAPTER_DATA_DIR)}.`)if (r.pid) console.log(` Stopped adapter process ${r.pid}.`)removeSignIn('reset', asked, chain)+ await endSignInOnServer(refreshToken)console.log('\n Start again with: harness login, then harness start\n')// The SECOND door onto the sign-out `logout` performs, and it clears MORE, so somebody running it// is if anything likelier to believe nothing is left. Same call, so the two cannot drift.diff --git a/cli/src/gateway/upstream.ts b/cli/src/gateway/upstream.tsindex 0da120df6..fdd236afd 100644--- a/cli/src/gateway/upstream.ts+++ b/cli/src/gateway/upstream.ts@@ -176,7 +176,8 @@ export class UpstreamLink {// Anything but a rejected refresh token (the backend down, another process refreshing) re-enters// the backoff: a flat second had every signed-in machine asking /api/auth/refresh once a second// for as long as the backend was away.- const delay = err instanceof AuthSessionError && err.code === 'INVALID_REFRESH' ? MAX_DELAY_MS : reconnectDelay(this.attempts++)+ // Nor does one SSO has stopped confirming ("sign in again"): it waits the longest, until the person signs in.+ const delay = err instanceof AuthSessionError && (err.code === 'INVALID_REFRESH' || err.code === 'SIGN_IN_AGAIN') ? MAX_DELAY_MS : reconnectDelay(this.attempts++)if (!this.closed) this.redialIn(delay)return}diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex ae4520e73..cacc9bb6f 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -127,13 +127,15 @@ describe('AuthSessionManager', () => {writeAuthSession({ ...baseSession(), clientId: 'harness-desktop' })await manager.accessToken()- expect(sent(0)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod', clientId: 'harness-desktop' })+ // An SSO sign-in's renewal also asks to become a Harness session (backend lib/ssoSession.ts).+ const harnessSession = { kind: 'computer', label: expect.any(String) }+ expect(sent(0)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod', clientId: 'harness-desktop', harnessSession })// The client outlives the refresh: the next one names it too.expect(readAuthSession()).toMatchObject({ accessToken: 'new-access', clientId: 'harness-desktop' })writeAuthSession(baseSession())await manager.accessToken()- expect(sent(1)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod' })+ expect(sent(1)).toEqual({ refreshToken: 'refresh-1', autonomousEnv: 'prod', harnessSession })})it('reads back only a client that is ours', async () => {@@ -203,6 +205,17 @@ describe('AuthSessionManager', () => {expect(err.message).toMatch(/Authentication service unavailable/) // the upstream's own words, kept})+ it('a renewal answered "sign in again" says so and keeps the session, unmarked', async () => {+ writeAuthSession({ ...baseSession(), accessToken: 'hna_old', refreshToken: 'hnr_1' })+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({+ success: false, error: { code: 'SIGN_IN_AGAIN', message: 'Sign in again: not confirmed for 7 days' },+ }), { status: 403 })))+ const manager = new AuthSessionManager('https://api.example.test')+ await expect(manager.accessToken()).rejects.toMatchObject({ code: 'SIGN_IN_AGAIN', message: expect.stringMatching(/harness login/) })+ expect(readAuthSession()).toMatchObject({ refreshToken: 'hnr_1' })+ expect(readSignedOut()).toBeNull()+ })+it('keeps the session when the refresh service is merely unavailable', async () => {// The other half of the same ambiguity, and the reason this must NOT be reclassified as// INVALID_REFRESH: that branch deletes the session, and deleting it on a transient blipdiff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 72f2f5715..ee000c7c8 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -1,5 +1,5 @@import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'-import { homedir } from 'os'+import { homedir, hostname } from 'os'import { join } from 'path'import { randomBytes } from 'node:crypto'@@ -46,7 +46,9 @@ export const knownSsoClientId = (raw: unknown): SsoClientId | undefined =>Object.values(SSO_CLIENT_IDS).find((id) => id === raw)export class AuthSessionError extends Error {- constructor(message: string, readonly code: 'MISSING' | 'INVALID_REFRESH' | 'UNAVAILABLE') {+ /** `SIGN_IN_AGAIN`: a Harness session SSO has not confirmed for longer than its grace (backend lib/ssoSession.ts). The+ * person is asked to sign in again; the session is kept, unmarked, so SSO coming back renews it. */+ constructor(message: string, readonly code: 'MISSING' | 'INVALID_REFRESH' | 'UNAVAILABLE' | 'SIGN_IN_AGAIN') {super(message)this.name = 'AuthSessionError'}@@ -293,6 +295,19 @@ async function withLock<T>(action: () => Promise<T>): Promise<T> {type RefreshResult = { token: string; refreshToken?: string; expiresIn?: number }+/**+ * What this computer asks the backend for in place of SSO tokens, when it signs in and when it renews an SSO sign-in:+ * a Harness session of its own (backend lib/ssoSession.ts), so an ordinary request never waits on the account+ * service. A backend from before it answers with the SSO tokens as ever, and those are kept.+ */+export const harnessSessionRequest = (): { kind: 'computer'; label: string } => ({ kind: 'computer', label: hostname().slice(0, 80) })++/** Whether renewing [session] asks to move it to a Harness session: an SSO sign-in's does. One that is a Harness+ * session already (`hnr_`, `htr_`) renews as one, and a QR or team sign-in is a session of its own kind. */+export function asksForHarnessSession(session: AuthSession): boolean {+ return session.kind !== 'team' && session.method !== 'qr' && !/^(hnr|htr)_/.test(session.refreshToken ?? '')+}+/*** The sentence an `UNAVAILABLE` refresh failure carries — and why it names `harness login` even* though it is classified as a service problem.@@ -332,6 +347,7 @@ async function refreshRequest(baseUrl: string, current: AuthSession, timeoutMs =refreshToken: current.refreshToken,autonomousEnv: current.autonomousEnv,...(current.clientId ? { clientId: current.clientId } : {}),+ ...(asksForHarnessSession(current) ? { harnessSession: harnessSessionRequest() } : {}),}),signal: AbortSignal.timeout(timeoutMs),})@@ -344,6 +360,10 @@ async function refreshRequest(baseUrl: string, current: AuthSession, timeoutMs =if (response.status === 401 || body.error?.code === 'REFRESH_TOKEN_INVALID') {throw new AuthSessionError('SSO refresh token is invalid. Run `harness login`.', 'INVALID_REFRESH')}+ if (body.error?.code === 'SIGN_IN_AGAIN') {+ throw new AuthSessionError('Sign in again: this computer\'s sign-in could not be confirmed with your Autonomous account '+ + 'for 7 days. Run `harness login`.', 'SIGN_IN_AGAIN')+ }if (!response.ok || body.success === false || typeof body.data?.token !== 'string' || !body.data.token) {throw new AuthSessionError(unavailableMessage(typeof body.error?.message === 'string' && body.error.message ? body.error.message : undefined),diff --git a/cli/src/services/accountLink.ts b/cli/src/services/accountLink.tsindex 649521949..38383ac17 100644--- a/cli/src/services/accountLink.ts+++ b/cli/src/services/accountLink.ts@@ -13,7 +13,7 @@ type Payload = Record<string, unknown>const text = (value: unknown): string => (typeof value === 'string' ? value : '')/** A frame in the core's answer: an object, or none. */const frameOf = (answer: Payload): Payload | null => (answer.frame && typeof answer.frame === 'object' ? answer.frame as Payload : null)-const SESSION_CODES = new Set(['MISSING', 'INVALID_REFRESH', 'UNAVAILABLE'])+const SESSION_CODES = new Set(['MISSING', 'INVALID_REFRESH', 'UNAVAILABLE', 'SIGN_IN_AGAIN'])/** `query` asks the core (`CoreConnection.query`, services/process.ts); it rejects when the link goes. */export function accountLink(query: (query: string, payload: Payload) => Promise<Payload>): Pick<CoreApi['account'], 'accessToken' | 'lane'> {@@ -25,7 +25,7 @@ export function accountLink(query: (query: string, payload: Payload) => Promise<throw new AuthSessionError(error instanceof Error ? error.message : 'not connected to the core', 'UNAVAILABLE')})if (typeof answer.token === 'string') return answer.token- const code = SESSION_CODES.has(text(answer.code)) ? text(answer.code) as 'MISSING' | 'INVALID_REFRESH' | 'UNAVAILABLE' : 'UNAVAILABLE'+ const code = SESSION_CODES.has(text(answer.code)) ? text(answer.code) as AuthSessionError['code'] : 'UNAVAILABLE'throw new AuthSessionError(text(answer.message) || 'the core could not hand out a token', code)},lane: {diff --git a/desktop/lib/viewer/direct_auth.dart b/desktop/lib/viewer/direct_auth.dartindex 408737eaa..d404fc026 100644--- a/desktop/lib/viewer/direct_auth.dart+++ b/desktop/lib/viewer/direct_auth.dart@@ -1,4 +1,7 @@+import 'dart:async';+import '../api/access_token_source.dart';+import '../logging/app_log.dart';import '../auth/auth_session.dart';import 'direct_auth_api.dart';@@ -60,10 +63,35 @@ class DirectAuth implements AccessTokenSource {});}- Future<void> signOut() {+ /// Signs this device out, and ends a Harness session on the server too. The server's part is+ /// best effort and not waited on: signing out never waits on, or fails over, the network.+ Future<void> signOut() async {final revision = ++_revision;_refreshing = null;- return _write(revision, session.clear);+ String? ended;+ await _write(revision, () async {+ ended = await session.refreshToken();+ await session.clear();+ });+ final refreshToken = ended;+ if (refreshToken != null &&+ DirectAuthApi.isHarnessRefreshToken(refreshToken)) {+ unawaited(_endOnServer(refreshToken));+ }+ }++ Future<void> _endOnServer(String refreshToken) async {+ var ended = false;+ try {+ ended = await api.revoke(refreshToken);+ } catch (_) {}+ if (!ended) {+ appLog.warn(+ 'auth',+ 'Could not end this sign-in on the server; it can no longer be used from here, '+ 'and ends on its own after 90 days unused.',+ );+ }}// A stale request is no longer allowed to decide that the CURRENT accountdiff --git a/desktop/lib/viewer/direct_auth_api.dart b/desktop/lib/viewer/direct_auth_api.dartindex 494e6074a..3de2cdf09 100644--- a/desktop/lib/viewer/direct_auth_api.dart+++ b/desktop/lib/viewer/direct_auth_api.dart@@ -63,27 +63,46 @@ class IssuedTokens {/// calls them (cli.ts `loginCommand`, authSession.ts `refreshRequest`). No bearer rides these:/// they are how one is got.class DirectAuthApi {- DirectAuthApi({required this.config, Dio? dio, String? clientId})- : clientId = clientId ?? ssoClientId,- _dio =- dio ??- attachHttpLog(- Dio(- BaseOptions(- baseUrl: config.apiBaseUrl,- connectTimeout: const Duration(seconds: 15),- receiveTimeout: const Duration(seconds: 30),- validateStatus: (status) => status != null && status < 600,- ),- ),- );+ DirectAuthApi({+ required this.config,+ Dio? dio,+ String? clientId,+ this.harnessSessionLabel,+ }) : clientId = clientId ?? ssoClientId,+ _dio =+ dio ??+ attachHttpLog(+ Dio(+ BaseOptions(+ baseUrl: config.apiBaseUrl,+ connectTimeout: const Duration(seconds: 15),+ receiveTimeout: const Duration(seconds: 30),+ validateStatus: (status) => status != null && status < 600,+ ),+ ),+ );final AppConfig config;/// The auth-service client this build signs in as (`auth/sso_client.dart`).final String clientId;++ /// What this device calls itself, set by a build that holds a Harness session in place of SSO+ /// tokens (backend `lib/ssoSession.ts`): a native one ([viewerSessionLabel]). It asks for one when+ /// it signs in and when it renews an SSO sign-in; a backend from before it answers with the SSO+ /// tokens as ever. Null — the browser build — asks for nothing.+ final String? harnessSessionLabel;final Dio _dio;+ Map<String, String>? get _harnessSessionAsk {+ final label = harnessSessionLabel;+ return label == null ? null : {'kind': 'viewer', 'label': label};+ }++ /// A refresh token Harness issued itself, not the account service.+ static bool isHarnessRefreshToken(String token) =>+ token.startsWith('hnr_') || token.startsWith('htr_');+static const _unavailable ='Could not renew your sign-in. That is usually the sign-in service having a moment — ''if it keeps happening, sign out and sign in again.';@@ -161,6 +180,7 @@ class DirectAuthApi {'state': state,'tx': tx,if (attribution.isNotEmpty) 'attribution': attribution,+ 'harnessSession': ?_harnessSessionAsk,},),);@@ -170,29 +190,45 @@ class DirectAuthApi {// -- signing in by a QR a signed-in phone approves (backend routes/qrSignIn.ts) --- Future<({String code, String pollToken, int expiresIn})> qrStart({required String label}) async {+ Future<({String code, String pollToken, int expiresIn})> qrStart({+ required String label,+ }) async {final data = unwrapApiResponse(- await _dio.post('/api/auth/qr/start', data: {'label': label, 'kind': 'viewer'}),+ await _dio.post(+ '/api/auth/qr/start',+ data: {'label': label, 'kind': 'viewer'},+ ),);- final code = data is Map ? data['code'] : null, poll = data is Map ? data['pollToken'] : null;+ final code = data is Map ? data['code'] : null,+ poll = data is Map ? data['pollToken'] : null;final expiresIn = data is Map ? data['expiresIn'] : null;if (code is! String || poll is! String || expiresIn is! int) {- throw const DirectAuthException('Sign-in by phone is not available here.');+ throw const DirectAuthException(+ 'Sign-in by phone is not available here.',+ );}return (code: code, pollToken: poll, expiresIn: expiresIn);}/// `pending`, `denied`, `expired`, or `approved` with the account's email.Future<({String status, String? email})> qrPoll(String pollToken) async {- final data = unwrapApiResponse(await _dio.post('/api/auth/qr/poll', data: {'pollToken': pollToken}));- final status = data is Map ? data['status'] : null, email = data is Map ? data['email'] : null;- return (status: status is String ? status : 'expired', email: email is String ? email : null);+ final data = unwrapApiResponse(+ await _dio.post('/api/auth/qr/poll', data: {'pollToken': pollToken}),+ );+ final status = data is Map ? data['status'] : null,+ email = data is Map ? data['email'] : null;+ return (+ status: status is String ? status : 'expired',+ email: email is String ? email : null,+ );}/// The same code, alive a while longer; null when it can live no longer.Future<int?> qrExtend(String pollToken) async {try {- final data = unwrapApiResponse(await _dio.post('/api/auth/qr/extend', data: {'pollToken': pollToken}));+ final data = unwrapApiResponse(+ await _dio.post('/api/auth/qr/extend', data: {'pollToken': pollToken}),+ );final expiresIn = data is Map ? data['expiresIn'] : null;return expiresIn is int ? expiresIn : null;} catch (_) {@@ -201,7 +237,9 @@ class DirectAuthApi {}Future<IssuedTokens> qrClaim(String pollToken) async {- final data = unwrapApiResponse(await _dio.post('/api/auth/qr/claim', data: {'pollToken': pollToken}));+ final data = unwrapApiResponse(+ await _dio.post('/api/auth/qr/claim', data: {'pollToken': pollToken}),+ );return IssuedTokens.fromData(data) ??(throw const DirectAuthException('Sign-in returned no access token.'));}@@ -232,6 +270,8 @@ class DirectAuthApi {'refreshToken': refreshToken,'autonomousEnv': autonomousEnv,'clientId': ?clientId,+ if (!isHarnessRefreshToken(refreshToken))+ 'harnessSession': ?_harnessSessionAsk,},);} on DioException {@@ -245,9 +285,32 @@ class DirectAuthApi {signedOut: true,);}+ // A Harness session the account service has not confirmed for 7 days (backend `lib/ssoSession.ts`):+ // the person is asked to sign in again, and the session is kept — not signed out — so the account+ // service coming back renews it.+ if (error['code'] == 'SIGN_IN_AGAIN') {+ throw const DirectAuthException(+ 'Sign in again: this sign-in could not be confirmed with your Autonomous account for 7 days.',+ );+ }final tokens = body['success'] == false? null: IssuedTokens.fromData(body['data']);return tokens ?? (throw const DirectAuthException(_unavailable));}++ /// Ends a Harness session on the server, as signing out does. False for an SSO refresh token,+ /// which is not the backend's to end, and when the server did not confirm it.+ Future<bool> revoke(String refreshToken) async {+ if (!isHarnessRefreshToken(refreshToken)) return false;+ try {+ final res = await _dio.post(+ '/api/auth/revoke',+ data: {'refreshToken': refreshToken},+ );+ return res.statusCode == 200;+ } on DioException {+ return false;+ }+ }}diff --git a/desktop/lib/viewer/platform_auth_native.dart b/desktop/lib/viewer/platform_auth_native.dartindex 4de12df0e..61930e18c 100644--- a/desktop/lib/viewer/platform_auth_native.dart+++ b/desktop/lib/viewer/platform_auth_native.dart@@ -1,4 +1,5 @@import '../auth/auth_session.dart';+import '../core/local_hostname.dart';import 'direct_auth.dart';import 'direct_auth_api.dart';@@ -6,3 +7,7 @@ DirectAuth createViewerAuth({required AuthSession session,required DirectAuthApi api,}) => DirectAuth(session: session, api: api);++/// A native build holds a Harness session in place of SSO tokens, named for this device+/// ([DirectAuthApi.harnessSessionLabel]).+String? viewerSessionLabel() => localHostnameOrNull() ?? 'Desktop app';diff --git a/desktop/lib/viewer/platform_auth_web.dart b/desktop/lib/viewer/platform_auth_web.dartindex cd0729c55..0287525d3 100644--- a/desktop/lib/viewer/platform_auth_web.dart+++ b/desktop/lib/viewer/platform_auth_web.dart@@ -7,6 +7,10 @@ import '../core/browser_lock.dart';import 'direct_auth.dart';import 'direct_auth_api.dart';+/// The browser build keeps its SSO sign-in: it asks for no Harness session+/// ([DirectAuthApi.harnessSessionLabel]).+String? viewerSessionLabel() => null;+DirectAuth createViewerAuth({required AuthSession session,required DirectAuthApi api,diff --git a/desktop/lib/viewer/viewer_services.dart b/desktop/lib/viewer/viewer_services.dartindex 10eb84d9e..31b7a6072 100644--- a/desktop/lib/viewer/viewer_services.dart+++ b/desktop/lib/viewer/viewer_services.dart@@ -40,7 +40,10 @@ class ViewerServices {final store = keys ?? ViewerKeyStore();final auth = createViewerAuth(session: session,- api: DirectAuthApi(config: config),+ api: DirectAuthApi(+ config: config,+ harnessSessionLabel: viewerSessionLabel(),+ ),);return ViewerServices._(keys: store,diff --git a/desktop/test/direct_auth_api_test.dart b/desktop/test/direct_auth_api_test.dartindex cc82c9016..ab7df1224 100644--- a/desktop/test/direct_auth_api_test.dart+++ b/desktop/test/direct_auth_api_test.dart@@ -134,4 +134,77 @@ void main() {'autonomousEnv': 'prod',});});++ group('a native build holds a Harness session in place of SSO tokens', () {+ late DirectAuthApi native;+ setUp(() {+ native = DirectAuthApi(+ config: AppConfig.dev,+ clientId: 'harness-desktop',+ harnessSessionLabel: 'Dee’s Mac',+ dio: Dio(BaseOptions(baseUrl: 'https://h.invalid'))+ ..httpClientAdapter = backend,+ );+ backend.reply = {+ 'success': true,+ 'data': {'token': 'issued'},+ };+ });++ const ask = {'kind': 'viewer', 'label': 'Dee’s Mac'};++ test('it asks for one when it signs in', () async {+ await native.exchange(code: 'c', state: 's', tx: 't');+ expect(backend.sent.single.body, {+ 'code': 'c',+ 'state': 's',+ 'tx': 't',+ 'harnessSession': ask,+ });+ });++ test('a sign-in from before the upgrade asks on its next renewal, '+ 'and a Harness session renews as one', () async {+ await native.refresh('sso-refresh', autonomousEnv: 'prod');+ expect(backend.sent.last.body, {+ 'refreshToken': 'sso-refresh',+ 'autonomousEnv': 'prod',+ 'harnessSession': ask,+ });+ await native.refresh('hnr_session', autonomousEnv: 'prod');+ expect(backend.sent.last.body, {+ 'refreshToken': 'hnr_session',+ 'autonomousEnv': 'prod',+ });+ });++ test('a session SSO has not confirmed for 7 days says "sign in again", '+ 'and is not signed out', () async {+ backend.reply = {+ 'success': false,+ 'error': {'code': 'SIGN_IN_AGAIN', 'message': 'Sign in again'},+ };+ await expectLater(+ native.refresh('hnr_session', autonomousEnv: 'prod'),+ throwsA(+ isA<DirectAuthException>()+ .having((e) => e.signedOut, 'signedOut', isFalse)+ .having((e) => e.message, 'message', contains('Sign in again')),+ ),+ );+ });++ test('signing out ends a Harness session on the server, and asks '+ 'nothing for an SSO one', () async {+ backend.reply = {+ 'success': true,+ 'data': {'revoked': true},+ };+ expect(await native.revoke('hnr_session'), isTrue);+ expect(backend.sent.single.path, '/api/auth/revoke');+ expect(backend.sent.single.body, {'refreshToken': 'hnr_session'});+ expect(await native.revoke('sso-refresh'), isFalse);+ expect(backend.sent, hasLength(1));+ });+ });}diff --git a/desktop/test/viewer_auth_lifecycle_test.dart b/desktop/test/viewer_auth_lifecycle_test.dartindex d32823cd3..b3dbb7cf9 100644--- a/desktop/test/viewer_auth_lifecycle_test.dart+++ b/desktop/test/viewer_auth_lifecycle_test.dart@@ -38,6 +38,20 @@ class _Api extends DirectAuthApi {/// The client each refresh named.final refreshClients = <String?>[];+ /// The refresh token each refresh presented.+ final refreshTokens = <String>[];++ /// The refresh tokens sign-outs asked the server to revoke.+ final revoked = <String>[];+ bool revokeFails = false;++ @override+ Future<bool> revoke(String refreshToken) async {+ if (revokeFails) throw const DirectAuthException('unreachable');+ revoked.add(refreshToken);+ return true;+ }+@overrideFuture<IssuedTokens> refresh(String refreshToken, {@@ -47,6 +61,7 @@ class _Api extends DirectAuthApi {final result = Completer<IssuedTokens>();refreshes.add(result);refreshClients.add(clientId);+ refreshTokens.add(refreshToken);return result.future;}@@ -192,6 +207,51 @@ void main() {},);+ test('a sign-in from before the upgrade stays signed in when its renewal '+ 'turns it into a Harness session, which renews as one', () async {+ // What today's app keeps after an SSO sign-in.+ await auth.signIn(_old);+ final first = auth.accessToken(force: true);+ await _until(() => api.refreshes.isNotEmpty);+ api.refreshes.single.complete(+ const IssuedTokens(+ token: 'hna_1',+ refreshToken: 'hnr_1',+ expiresIn: 3600,+ ),+ );+ expect(await first, 'hna_1');+ expect(await session.refreshToken(), 'hnr_1');+ expect(await auth.hasSession(), isTrue);++ final second = auth.accessToken(force: true);+ await _until(() => api.refreshes.length == 2);+ api.refreshes.last.complete(const IssuedTokens(token: 'hna_2'));+ expect(await second, 'hna_2');+ expect(api.refreshTokens, ['old-refresh', 'hnr_1']);+ });++ test('signing out ends a Harness session on the server; an SSO one asks '+ 'nothing, and an unreachable server still signs out', () async {+ await auth.signIn(+ const IssuedTokens(token: 'hna_1', refreshToken: 'hnr_1'),+ );+ await auth.signOut();+ expect(api.revoked, ['hnr_1']);+ expect(await auth.hasSession(), isFalse);++ await auth.signIn(_old);+ await auth.signOut();+ expect(api.revoked, ['hnr_1']);++ api.revokeFails = true;+ await auth.signIn(+ const IssuedTokens(token: 'hna_2', refreshToken: 'hnr_2'),+ );+ await auth.signOut();+ expect(await auth.hasSession(), isFalse);+ });+test('refreshes coalesce and retain unrotated refresh tokens', () async {await auth.signIn(_old);final first = auth.accessToken(force: true);diff --git a/docs/plans/2026-10-28-sso-then-harness-session.md b/docs/plans/2026-10-28-sso-then-harness-session.mdnew file mode 100644index 000000000..bebd607f5--- /dev/null+++ b/docs/plans/2026-10-28-sso-then-harness-session.md@@ -0,0 +1,89 @@+# Sign in through SSO once, then hold a Harness session++Ken (GO 10-28). People still sign in through Autonomous SSO. After that, the CLI and Desktop hold a Harness-issued+session (`hna_`/`hnr_`, the kind the phone gets from the QR handoff), so an ordinary request no longer waits on+the account service, and SSO being slow or down no longer breaks signed-in people.++Code: `backend/src/lib/ssoSession.ts` (the rules below), `lib/harnessSession.ts`, `routes/auth.ts`, billing in+`routes/machines.ts`; `cli/src/lib/authSession.ts`, `cli/src/cli.ts`; `desktop/lib/viewer/direct_auth*.dart`.++## How it works++- **Getting one.** A client asks for `harnessSession: { kind, label }` on the sign-in exchange, or on an SSO renewal.+ The backend checks the SSO token once, as today, and answers with a Harness session in place of the SSO tokens.+ The CLI asks for a `computer` session, which may connect as a machine. A native Desktop build that signs in by+ itself asks for a `viewer` session. The browser build asks for nothing and keeps its SSO sign-in.+- **The SSO sign-in behind it.** The person's SSO refresh token, and the last access token it gave, are stored on the+ session, encrypted with the credential key (`lib/machineCredential.ts`). They are never returned to a client and+ never logged. They are deleted when the session ends.+- **Lifetimes.** Access token 1 hour. The refresh token is not rotated (the QR session's rule) and lasts 90 days idle.+- **Hourly re-check.** A renewal of the session re-checks the SSO sign-in at most once an hour:+ - SSO renews it: the rotated SSO refresh token is saved, and the session goes on.+ - SSO refuses the token it holds, with no earlier renewal left unfinished: the person signed out of Autonomous, or+ the account was disabled. The session ends, so access ends within about 2 hours (re-check plus access lifetime).+ - Anything else counts as SSO unavailable, never a sign-out: slow, down, 5xx, an answer for another account, an+ unreadable identity, or a refusal after an unfinished renewal. The session goes on for 7 days from its last good+ check. After that, renewals answer `SIGN_IN_AGAIN` (403), which the CLI and Desktop show as "Sign in again". The+ session is not ended, so SSO coming back renews it, but nobody is left retrying silently forever.+- **Rotation safety.** A renewal takes the session's lock in Redis (`SET NX`, released by compare-and-delete), and+ marks the session (`ssoRenewingAt`) before asking SSO. Only saving SSO's answer clears the mark. A mark left+ behind means a rotated token may have been lost on the way, so a refusal of the stored one proves nothing.+- **Only live sessions are written.** Every write a renewal makes is conditional on the session not being revoked.+ A session signed out while SSO was answering gets nothing written back, and its renewal answers 401.+- **Only confirmed access tokens are kept.** An SSO access token is stored only after SSO's profile service has+ confirmed whose it is. When that check cannot be made, the rotated refresh token is kept (losing it would lose the+ sign-in), but the access token is not, so billing can never forward an unconfirmed one.+- **Moving over.** Today's SSO sign-ins move on their next ordinary renewal, with no sign-in prompt. If the session+ cannot be made, the renewal answers with the SSO tokens as before, so a rotated SSO refresh token is never lost.+- **Signing out.** `harness logout`, and Desktop sign-out, end the Harness session on the server: best effort,+ bounded, and the CLI says so when the server cannot be reached. Device removal already ends it.+- **Billing.** Billing and machine deletion forward an SSO access token to the account service. For these sessions,+ the backend uses the confirmed one it keeps, renewed under the same lock. A second call that finds a renewal under+ way waits for it (up to the lock's 60 s) and reads its answer. Other Harness sessions are refused as before.+- **Replacing a sign-in.** `harness login --force` and `harness reset` also end the previous Harness session on the+ server, as `harness team on` does.+- **No new power.** These sessions name no computer, so they never count as "this computer's own sign-in" for+ turning a computer into a team machine; that still needs the machine-key proof, as an SSO sign-in does.++## Design (docs/feature-design-rules.md)++Reviewed revision: see the PR. Reviewer: two independent security reviews (Ken delegated sign-off to the Swarm).++1. **Growth.** One `harness_sessions` row per sign-in. Ending a session sets `expiresAt` to now, and a TTL index the+ worker creates (`harness_session_expiry`) deletes a row 30 days after `expiresAt`: ended, or idle past 90 days.+ Before this, nothing deleted these rows. Redis keys: the access token (1 hour TTL) and the renewal lock (60 s TTL).+2. **Concurrency.** The SSO renewal locks per session in Redis. Under the lock it reads the row again, writes the+ mark, calls SSO, and saves the answer and clears the mark in one update. Every one of those writes is guarded on+ the row still being live, so a sign-out that lands meanwhile wins (tested: a revoke while SSO answers). A second renewal finds the lock taken and+ goes on without asking SSO, within the grace. A lost reply or failed save leaves the mark, which turns a later+ refusal into "unavailable". Tested: two renewals at once ask SSO once; removing the lock fails that test.+3. **Read cost.** An ordinary request is unchanged for a Harness token: one Redis read and one session read by id.+ It no longer reads the SSO profile (or its cache). A renewal reads the session once; once an hour it adds one+ SSO token call, one profile read and one update. No list reads.+4. **Scale.** SSO calls drop from per-request (cached) to one per signed-in client per hour. At 10x clients that is+ still one SSO call per client-hour. Warns first: the `sso re-check unavailable` warning rate and 503s from+ `/api/auth/refresh`.+5. **Compatibility.** Old clients send no `harnessSession` and get exactly today's answers (tested). A new client+ on an old backend: the field is ignored and SSO tokens come back, which are kept. The new fields are read only by+ `lib/ssoSession.ts`. Existing readers of the session rows (revoke paths, device key log, team conversion, Grid+ profile, machine service) were found by searching and keep their meaning; the revoke paths now also clear the+ SSO fields.+6. **Migration and rollback.** No data migration: the fields are optional and new sessions write them. Deploy the+ backend first; clients ask on their next renewal. On rollback, the previous backend already accepts and renews+ `hna_`/`hnr_` sessions, so moved-over clients stay signed in. **But an older backend never re-checks SSO**: while it+ runs, a person who signs out of Autonomous or whose account is disabled keeps a moved-over session (up to its 90+ idle days) until this release is back, and billing for these sessions answers "needs your Autonomous sign-in".+ Keep a rollback short, or end these sessions by hand (`harness_sessions` rows with `ssoRefresh` set). Not checked+ on a production restore.+7. **Audience.** The stored SSO tokens leave the backend only toward the account service: for a renewal, or for+ billing for that session's own user (`ssoAccessTokenFor` checks the user and that the session is live).+ No route returns them.+8. **Identity.** Each session acts for the account SSO verified when it was made, and each re-check confirms SSO+ still answers for that account. An answer for another account is refused (counted as unavailable). Never the+ machine owner's login: the CLI's session is the person who signed in on it.+9. **Failure.** SSO down: people stay signed in, and the backend logs `sso re-check unavailable` per session. Past+ the grace, the CLI's status and the Desktop say "Sign in again"; the daemon retries at its longest backoff. Credential key missing or store failing: the sign-in+ falls back to SSO tokens and logs `harness session not made`. A server sign-out that cannot be reached: the CLI says+ so, and the Desktop logs it.+10. **Platforms.** Backend: Linux. CLI: macOS, Linux and Windows, with tokens in the same `~/.harness/auth/session.json`+ (0600). Desktop native builds keep tokens in the app's existing session store. The browser build is unchanged.