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
import { env } from '../config/env.js'
import {
isProvisionalUserEmail,
normalizeUserEmail,
userService,
} from '../services/UserService.js'
import {
autonomousEnvironmentConfig,
storedAutonomousEnvironment,
type AutonomousEnvironment,
} from './autonomousEnvironment.js'
import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'
import { createCircuitBreaker, CircuitOpenError, type CircuitBreaker } from './circuitBreaker.js'
import { logger } from '../utils/logger.js'
import { isHarnessAccessToken } from './harnessTokenFormat.js'
import { scheduleGoogleSubjectFill } from './googleSubject.js'
import type { SignInAttribution } from './signInAttribution.js'
/** Internal identity attached to authenticated backend requests and user WebSockets. */
export interface AuthUser {
sub: string // internal database user id
email: string
role: string
autonomousEnv: AutonomousEnvironment
/** Set when the token is one Harness issued itself (lib/harnessSession.ts), not an Autonomous one. */
harnessSessionId?: string
/** With [harnessSessionId]: a computer signed in by QR may connect as a machine; a viewer may not. A team
* session (lib/teamSession.ts) may connect only as its own computer's machine, and do strictly less. */
harnessSessionKind?: 'viewer' | 'computer' | 'team'
/** With a team session: the computer it is bound to (normalized). With a computer session signed in by QR: the
* computer it signed in as, which lets it turn itself into a team machine (routes/auth.ts). */
harnessComputerId?: string
}
export interface SsoProfile {
id: string
email: string
}
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'
/** 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)
this.name = 'SsoAuthError'
}
}
export function bearerToken(header: string | undefined): string | undefined {
if (!header) return undefined
const m = /^Bearer\s+(.+)$/i.exec(header)
return m ? m[1].trim() : undefined
}
type FetchLike = typeof fetch
// The cross-process store is attached by the server at startup rather than imported here: the Redis
// module connects on import, and this file is imported by everything that authenticates.
let sharedProfileStore: SharedProfileStore | null = null
const profileCache = createSsoProfileCache({
ttlMs: env.SSO_PROFILE_CACHE_TTL_MS,
shared: () => sharedProfileStore,
staleGraceMs: env.SSO_PROFILE_STALE_GRACE_MS,
servesStale: (err) => err instanceof SsoAuthError && err.code === 'AUTH_SERVICE_UNAVAILABLE',
})
// Per account plane: after a few validations in a row that the profile service could not answer, the next ones fail
// at once for a while instead of each waiting out the timeout (Stability 3.5). A rejected token is an answer.
const SSO_BREAKER_FAILURES = 5
const SSO_BREAKER_OPEN_MS = 10_000
const ssoBreakers = new Map<AutonomousEnvironment, CircuitBreaker>()
function ssoBreaker(autonomousEnv: AutonomousEnvironment): CircuitBreaker {
let breaker = ssoBreakers.get(autonomousEnv)
if (!breaker) {
breaker = createCircuitBreaker({
name: `sso-profile:${autonomousEnv}`,
failureThreshold: SSO_BREAKER_FAILURES,
openMs: SSO_BREAKER_OPEN_MS,
isFailure: (err) => !(err instanceof SsoAuthError) || err.code === 'AUTH_SERVICE_UNAVAILABLE',
onStateChange: (state) => {
if (state === 'open') logger.warn('[sso] profile service unreachable; failing fast', { autonomousEnv })
else logger.info('[sso] profile service circuit', { autonomousEnv, state })
},
})
ssoBreakers.set(autonomousEnv, breaker)
}
return breaker
}
async function validateWithBreaker(token: string, autonomousEnv: AutonomousEnvironment): Promise<SsoProfile> {
try {
return await ssoBreaker(autonomousEnv).run(() => fetchSsoProfile(token, autonomousEnv))
} catch (err) {
if (err instanceof CircuitOpenError) throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')
throw err
}
}
/** Test seam. */
export function resetSsoBreakers(): void {
ssoBreakers.clear()
}
export function useSharedSsoProfileStore(store: SharedProfileStore | null): void {
sharedProfileStore = store
}
// A BFF that predates the identity route answers it 404 every time. Remember that per account plane
// for a few minutes rather than asking twice before every validation.
const IDENTITY_MISSING_TTL_MS = 5 * 60_000
const identityMissingUntil = new Map<AutonomousEnvironment, number>()
export function clearSsoProfileCache(): void {
profileCache.clear()
identityMissingUntil.clear()
}
/** Validate the SSO access token against the Autonomous profile service. */
export async function fetchSsoProfile(
token: string,
autonomousEnvOrFetch: AutonomousEnvironment | FetchLike = 'prod',
fetchOverride?: FetchLike,
): Promise<SsoProfile> {
// Preserve the old test/helper call shape fetchSsoProfile(token, fetchImpl) while production code
// always supplies the environment explicitly.
const autonomousEnv = typeof autonomousEnvOrFetch === 'function' ? 'prod' : autonomousEnvOrFetch
const fetchImpl = typeof autonomousEnvOrFetch === 'function' ? autonomousEnvOrFetch : (fetchOverride ?? fetch)
const { ssoProfileUrl, ssoIdentityUrl } = autonomousEnvironmentConfig(autonomousEnv)
// One deadline for the whole validation: the profile fallback gets what the identity call left, not a second timeout.
const deadline = AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS)
const ask = async (url: string): Promise<Response> => {
if (deadline.aborted) throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')
try {
return await fetchImpl(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Location: 'en-US',
Authorization: `Bearer ${token}`,
},
signal: deadline,
})
} catch {
throw new SsoAuthError('SSO profile service unavailable', 'AUTH_SERVICE_UNAVAILABLE')
}
}
// The identity endpoint answers from the token alone; the profile endpoint costs the storefront a
// customer read and a cart read per call. Same envelope, same two fields.
//
// Identity is an optimisation, never a dependency: whenever it cannot give an ANSWER — not deployed
// (404), failing (5xx), unreachable — the profile URL is asked instead, exactly as before it existed.
// A 401/403 is an answer, and is final.
const useIdentity = !!ssoIdentityUrl && (identityMissingUntil.get(autonomousEnv) ?? 0) <= Date.now()
let res: Response | undefined
if (useIdentity) {
res = await ask(ssoIdentityUrl!).catch(() => undefined)
if (res?.status === 404) identityMissingUntil.set(autonomousEnv, Date.now() + IDENTITY_MISSING_TTL_MS)
if (res && (res.status === 404 || res.status >= 500)) res = undefined
}
res ??= await ask(ssoProfileUrl)
if (res.status === 401 || res.status === 403) {
throw new SsoAuthError('Invalid or expired SSO access token', 'INVALID_TOKEN')
}
if (!res.ok) {
throw new SsoAuthError(`SSO profile service returned ${res.status}`, 'AUTH_SERVICE_UNAVAILABLE')
}
let raw: unknown
try { raw = await res.json() } catch {
throw new SsoAuthError('SSO profile service returned invalid JSON', 'AUTH_SERVICE_UNAVAILABLE')
}
const body = raw as { status?: unknown; message?: unknown; data?: { id?: unknown; email?: unknown } }
if (body.status !== 1 || typeof body.data?.id !== 'string' || !body.data.id ||
typeof body.data.email !== 'string' || !body.data.email) {
const message = typeof body.message === 'string' ? body.message : ''
if (/invalid|expired|unauthorized/i.test(message)) {
throw new SsoAuthError('Invalid or expired SSO access token', 'INVALID_TOKEN')
}
throw new SsoAuthError('SSO profile service returned an invalid profile', 'AUTH_SERVICE_UNAVAILABLE')
}
return { id: body.data.id, email: body.data.email }
}
/** Optional metadata is read only AFTER the profile service has authenticated this access token. */
function accessTokenMetadata(token: string): { name?: string; roles?: string[] } {
try {
const part = token.split('.')[1]
if (!part) return {}
const raw = JSON.parse(Buffer.from(part, 'base64url').toString('utf8')) as Record<string, unknown>
const flat: Record<string, unknown> = {}
for (const container of ['ext_info', 'user', 'profile', 'data', 'claims', 'userInfo', 'user_info']) {
const value = raw[container]
if (value && typeof value === 'object') Object.assign(flat, value)
}
Object.assign(flat, raw)
const pick = (...keys: string[]): string | undefined => {
for (const key of keys) {
const value = flat[key]
if (value != null && value !== '') return String(value)
}
return undefined
}
const given = pick('given_name', 'givenName', 'firstName', 'first_name')
const family = pick('family_name', 'familyName', 'lastName', 'last_name')
const name =
pick('name', 'fullName', 'full_name', 'displayName', 'display_name', 'nickname', 'user_name', 'username') ??
([given, family].filter(Boolean).join(' ') || undefined)
const roles = Array.isArray(flat.roles) ? flat.roles.map(String) : undefined
return { ...(name ? { name } : {}), ...(roles ? { roles } : {}) }
} catch {
return {}
}
}
/** Validate the token, mirror the external identity, then return the app's internal user identity. */
/**
* @param allowHarnessSession Accept a Harness-issued token (lib/harnessSession.ts). `'computer'` where
* the caller connects AS a machine: only a session a phone approved for a computer (its QR sign-in)
* may — a phone's own session is a viewer's, never a daemon's. FALSE refuses every Harness session.
*
* @param allowTeamSession Accept a team session (lib/teamSession.ts) too. Deny by default: only a caller
* that confines one to its own machine passes TRUE — the REST gate (middlewares/authMiddleware.ts, with
* its allowlist) and the machine socket (lib/adapterWs.ts, its bound computer). Everywhere else a team
* session is refused with `TEAM_SESSION_LIMITED`, whatever `allowHarnessSession` says.
*
* @param enforceEnv Gate the caller on the account plane their user row is stamped with. TRUE for the
* web, which can be pointed at either plane and must not let the two identities cross.
*
* FALSE for a surface that is production-only by construction — today that is `/api/mobile/*`. There
* the token is always validated against PROD SSO, so a staging token simply fails the profile fetch;
* what the flag drops is only the refusal to serve a user whose row happens to be stamped `stag`.
* Those rows are legacy (the schema backfilled every pre-existing user to staging), and rejecting
* them would lock long-standing customers out of the mobile app for a reason that has nothing to do
* with them. It is not a widening of access: the identity served is still the one prod SSO just
* verified, and `upsertFromSso` never rewrites `autonomousEnv`, so the user's web experience is
* untouched.
*/
export async function authenticateAccessToken(
token: string,
autonomousEnv: AutonomousEnvironment = 'prod',
{
enforceEnv = true,
allowHarnessSession = true,
allowTeamSession = false,
signUpAttribution,
learnGoogleSubject = true,
}: {
enforceEnv?: boolean
allowHarnessSession?: boolean | 'computer'
allowTeamSession?: boolean
/** The sign-in's tags (lib/signInAttribution.ts), kept on the account only if this creates it. */
signUpAttribution?: SignInAttribution
/** FALSE where the caller reads the profile live itself (`GET /api/grid/profile`), so one request
* is one read and one stored-versus-live line, not two. */
learnGoogleSubject?: boolean
} = {},
): Promise<AuthUser> {
// A sign-in Harness issued itself — a phone signed in by scanning a computer's QR. It names its
// user outright, so there is no account plane to choose and nothing to ask the account service.
// Loaded on first use: that module holds Redis, which connects on import (see the store above).
if (isHarnessAccessToken(token)) {
if (!allowHarnessSession) throw new SsoAuthError('This connection needs an Autonomous sign-in', 'INVALID_TOKEN')
const { authenticateHarnessAccessToken } = await import('./harnessSession.js')
const user = await authenticateHarnessAccessToken(token)
if (user.harnessSessionKind === 'team') {
if (!allowTeamSession) throw new SsoAuthError('This connection is not available to a team sign-in', 'TEAM_SESSION_LIMITED')
return user
}
if (allowHarnessSession === 'computer' && user.harnessSessionKind !== 'computer') {
throw new SsoAuthError('This connection needs a computer sign-in', 'INVALID_TOKEN')
}
return user
}
const profile = await profileCache.resolve(token, autonomousEnv, () => validateWithBreaker(token, autonomousEnv))
const metadata = accessTokenMetadata(token)
const email = normalizeUserEmail(profile.email)
if (!email) throw new SsoAuthError('SSO profile service returned an invalid profile', 'AUTH_SERVICE_UNAVAILABLE')
// Email is the account identity across Autonomous planes. Production may additionally claim the
// deterministic provisional row created when an SDS device connected before its owner's first login.
const byEmail = await userService.findByEmail(email)
const byProdExternal = !byEmail && autonomousEnv === 'prod'
? await userService.findByExternal(profile.id)
: null
const provisional = !!byProdExternal && isProvisionalUserEmail(byProdExternal.email)
const existing = byEmail ?? (provisional ? byProdExternal : null)
if (enforceEnv && !existing && autonomousEnv === 'stag') {
throw new SsoAuthError('Staging access is not enabled for this user', 'AUTONOMOUS_ENV_NOT_ALLOWED', 'prod')
}
if (enforceEnv && existing && !provisional) {
const requiredEnv = storedAutonomousEnvironment(existing.autonomousEnv)
if (requiredEnv !== autonomousEnv) {
throw new SsoAuthError('Sign in through the configured Autonomous environment', 'AUTONOMOUS_ENV_MISMATCH', requiredEnv)
}
}
const user = await userService.upsertFromSso({
externalId: profile.id,
email,
autonomousEnv,
...metadata,
...(signUpAttribution ? { signUpAttribution } : {}),
}, { existing })
// Learn the account's Google subject while an Autonomous token is in hand, so a computer of the same
// account signed in by QR can be answered later (lib/googleSubject.ts). Not awaited, never throws.
// Here and not in the REST hook, because a daemon that only holds a socket authenticates here too.
if (learnGoogleSubject) scheduleGoogleSubjectFill(token, user, autonomousEnv)
return { sub: user.id, email: user.email, role: user.role, autonomousEnv }
}