Skip to content

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

refactor: replace harness join with harness login and harness start commands and implement durable SSO session management

0xken15cc751de4d269
diff --git a/README.md b/README.md
index 7bc69ad54..d117ead19 100644
--- a/README.md
+++ b/README.md
@@ -62,13 +62,13 @@ To get started, run this:
```bash
curl -fsSL https://harness.autonomous.ai/install.sh | bash
-harness auth device
+harness login
+harness start
```
-`harness auth device` prints a six-character code and a link. Approve it in a browser where you are
-signed in and this computer is connected — there is no token to copy, and re-running it on the same
-computer reconnects it to the same machine rather than making a new one. If you already have a
-machine's token, `harness join <token>` still works.
+`harness login` opens your browser for SSO and stores this computer's session. `harness start` refreshes
+that session when needed and connects the local adapter. There is no token to copy; the durable computer
+id keeps later starts attached to the same machine.
Runs on **macOS and Linux** (Ubuntu 22.04+ verified). Node ≥ 20 and tmux and/or Herdr are the
prerequisites — see [`cli/README.md`](cli/README.md#supported-platforms).
@@ -97,7 +97,8 @@ Your agents stay your processes, on your hardware, with your credentials.
┌───────────────────────┼───────────────────────┐
│ │ │
your laptop your server your platform
- `harness join` `harness join` your HTTP API
+ `harness login` + `harness login` + your HTTP API
+ `harness start` `harness start`
│ │ │
claude · codex hermes · muse agents running on
cursor · amp · … opencode · kilo · your own servers
diff --git a/cli/README.md b/cli/README.md
index b64a4958b..fa22a492c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -30,29 +30,32 @@ Windows is not supported.
## Install & run (`harness`)
-Prerequisite: **Node ≥ 20**. Create or open a remote machine in the web UI first, then copy its connect
-token into the installer:
+Prerequisite: **Node ≥ 20**. Install the CLI, then sign in once with the same SSO account used by
+Harness:
```bash
-curl -fsSL https://harness.autonomous.ai/install.sh | bash -s -- <token>
+curl -fsSL https://harness.autonomous.ai/install.sh | bash
```
(The installer is a first-party hosted script; it downloads the published bundle and writes the
`~/.local/bin/harness` command.)
```bash
-harness join <token> # connect this computer to an existing machine
-harness join # reconnects with the saved credential
+harness login # opens browser SSO and saves this computer's session
+harness login --force # stop the daemon and sign in as a different SSO account
+harness start # starts the adapter from the saved SSO session
+harness start -f # foreground mode for a supervisor; logs to stdout
harness status # is it running? shows pid + the chat link
harness stop # stop the background adapter
harness version # print the installed version
-harness unjoin # leave the machine (also removes it on the web) + clear the saved credential
-harness join -f # reconnect in the FOREGROUND (for a supervisor: pm2/systemd), logs to stdout
+harness logout # stop the adapter and clear this computer's SSO session
```
-`join` prints a uniform info block (status, backend, pid, logs, and the **web chat link**
-`WEB_URL/machine/<agentId>`) then detaches; raw logs go to `${ADAPTER_DATA_DIR}/harness.log`. The
-credential is persisted to `${ADAPTER_DATA_DIR}/token`, so later runs are just `harness join`.
+`login` uses the browser's native loopback SSO flow. Its access token, refresh token, expiry and
+backend-resolved machine id are stored atomically with owner-only permissions in
+`~/.harness/auth/session.json`; the immutable computer id lives separately at
+`~/.harness/computer-id`. Later `harness start` invocations reuse and refresh that session as needed.
+Raw daemon logs go to `${ADAPTER_DATA_DIR}/harness.log`.
The log is **capped at 10 MB**: the daemon checks the size every minute and, over the cap, rewrites the
file with the newest half (the oldest lines are dropped, marked by a `[log] trimmed` line at the top).
@@ -69,8 +72,8 @@ Custom Herdr-capable builds must keep self-update disabled or use a fork-owned s
`ADAPTER_UPDATE_URL` until that build is available in the configured upstream manifest. Otherwise the
updater can legitimately replace the custom bundle with a release that lacks its terminal support.
-**From source (dev):** `cd this package && npm install && npm run build && node dist/cli.js join <token>`
-(or `npm run dev -- join` via tsx — always foreground; self-update is off in dev). `npm run bundle`
+**From source (dev):** `cd this package && npm install && npm run build && node dist/cli.js login`
+(or `npm run dev -- login` via tsx — always foreground; self-update is off in dev). `npm run bundle`
produces the single-file release artifact.
**Install your build as `harness` (no release):** `bash scripts/install-cli.sh` bundles this
@@ -79,7 +82,7 @@ daemon on it, so `harness` on this computer means your code without publishing a
turned **off** in the command shim it writes (otherwise the published release overwrites your build within
the minute). See [`RELEASE.md`](RELEASE.md#local-install-no-upload).
-After joining, start each agent yourself in tmux or Herdr with its normal vendor command. Harness
+After signing in, start each agent yourself in tmux or Herdr with its normal vendor command. Harness
observes the process; it does not launch the CLI or choose its permission/trust flags:
```bash
@@ -185,10 +188,11 @@ reported as such, not described as exercised.
| var | default | meaning |
|-----|---------|---------|
| `BACKEND_WS_URL` | `wss://harness-api.autonomous.ai` | backend to dial (`/api/adapter-ws`) |
-| `ADAPTER_TOKEN` | *(unset)* | pair token override (else CLI arg / saved file) |
+| `AUTONOMOUS_ENV` | `prod` | SSO environment: `prod` or `stag` |
+| `ADAPTER_COMPUTER_ID` | *(unset)* | pin the stable local computer id for an ephemeral host; never written to disk |
| `PORT` | `18473` | localhost port for the hook callbacks (FIXED — if taken, the adapter reports it rather than picking a random port) |
| `CLAUDE_PROJECTS_DIR` | `~/.claude/projects` | where Claude writes session JSONL |
-| `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry + token persistence |
+| `ADAPTER_DATA_DIR` | `~/.harness/cli/data` | registry and daemon-local state (SSO session is always `~/.harness/auth/session.json`) |
| `DISABLE_HOOK_INSTALL` | `false` | skip auto-installing the claude hooks |
| `TERMINAL_BACKENDS` | *(auto)* | pin the set: `tmux`, `herdr`, or `tmux,herdr`. Unset = every usable backend |
| `HERDR_SESSIONS` | *(auto)* | pin an allowlist. Unset = every running Herdr session is adopted |
diff --git a/cli/scripts/install-cli.sh b/cli/scripts/install-cli.sh
index 6c1cebc2f..73f2d1a0d 100755
--- a/cli/scripts/install-cli.sh
+++ b/cli/scripts/install-cli.sh
@@ -19,7 +19,7 @@
# It used to default to OFF, which pinned the computer silently: a new release would land in the manifest
# and simply never arrive, and the only clue was `harness update` working by hand while nothing happened
# on its own. `--no-updates` still gives you that, deliberately — it exports ADAPTER_UPDATE_DISABLE=true
-# in the launcher, switching off both the 60s poll and `harness join`'s update-before-connect (cli.ts
+# in the launcher, switching off both the 60s poll and `harness start`'s update-before-connect (cli.ts
# `stageLatestBundle`). To rejoin the release train from a pinned install, re-run this without the flag,
# or the public installer:
# curl -fsSL https://harness.autonomous.ai/install.sh | bash
@@ -169,11 +169,11 @@ echo " launcher: $LAUNCHER$([ "$KEEP_UPDATES" -eq 1 ] && echo ' (self-update
if [ "$WAS_RUNNING" -eq 1 ] && [ "$DO_RESTART" -eq 1 ]; then
echo ">> reconnecting on the new build…"
sleep 1 # grace for the backend to release the one-machine claim (as `harness update` does)
- "$LAUNCHER" join
+ "$LAUNCHER" start
elif [ "$WAS_RUNNING" -eq 1 ]; then
- echo " (daemon stopped and NOT restarted — run: harness join)"
+ echo " (daemon stopped and NOT restarted — run: harness start)"
else
- echo " (no daemon was running — run \`harness join\` to connect, or \`harness join <token>\` on a fresh machine)"
+ echo " (no daemon was running — run \`harness login\` if needed, then \`harness start\`)"
fi
# --- Step 7: PATH hint (this script deliberately does not edit your shell rc) ---
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 8916ac775..8e2505bcc 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -9,15 +9,15 @@
* WS ping/pong keep-alive + a 15s app-level `{t:'ping'}` that refreshes the backend presence
* key, and a bounded FIFO queue for client-facing outbound frames.
*
- * Auth: the connect token (agent apiKey) rides as the first WS subprotocol.
+ * Auth: the SSO access token rides as the first WS subprotocol.
*/
import { WebSocket } from 'ws'
import { stat, readFile } from 'fs/promises'
import { isAbsolute, join } from 'path'
import { hostname } from 'os'
-import { createHash } from 'crypto'
import { env } from './config/env.js'
+import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { ENGINES, type AgentEngine } from './engines/types.js'
@@ -256,7 +256,11 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strin
export class BackendSocket {
private ws: WebSocket | null = null
- private token: string
+ private connecting = false
+ private retryingAuth = false
+ private readonly auth: AuthSessionManager
+ /** Constructor-without-auth is retained for isolated unit tests only. */
+ private readonly testToken?: string
private url: string
private attempts = 0
private closed = false
@@ -300,13 +304,13 @@ export class BackendSocket {
* programmatic answer channel the way the hosted runtime’s brain does. */
onQuestionAnswer: ((payload: { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }) => void) | null = null
/** Called when this machine was deleted/revoked (a `machine_revoked` down-frame, or a 401/403 on the
- * upgrade) — cli clears the saved token and shuts the adapter down instead of retrying forever. */
+ * upgrade) — CLI clears the saved SSO session and shuts down instead of retrying forever. */
onRevoked: (() => void) | null = null
/** Called with the machine's display name (`machine_meta` down-frame: seeded on connect, pushed on a
* web rename; null = unnamed) — cli mirrors it to a local file for `harness status`. */
onMachineMeta: ((name: string | null) => void) | null = null
- /** Called when this machine is already connected from ANOTHER machine (HTTP 409 on the upgrade) — the
- * credential is valid, just in use elsewhere, so cli keeps the token and stops (no retry loop). */
+ /** Called when this machine is already connected from ANOTHER computer (HTTP 409 on the upgrade) — the
+ * SSO session is valid, so CLI keeps it and stops without a retry loop. */
onBusy: (() => void) | null = null
/** Answers the device `project_recent` RPC (cli.ts wires this to CommanderMirror.recent). */
recentProvider: RecentProvider | null = null
@@ -316,7 +320,7 @@ export class BackendSocket {
onRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null = null
/** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */
readonly e2ee: E2eeManager
- /** agentId = sha256(token)[:32] — exposed for the local dashboard status. */
+ /** Backend-resolved machine id, persisted by the SSO login preflight. */
readonly machineId: string
/** The ONE place commander presence changes. Both callers — the `__clients` snapshot and `onGone` (our
@@ -364,16 +368,17 @@ export class BackendSocket {
this.e2ee.dashboardPort = port
}
- constructor(token: string, onStatus: (connected: boolean) => void = () => {}, computerId = '') {
- this.token = token
+ constructor(machineId: string, auth?: AuthSessionManager, onStatus: (connected: boolean) => void = () => {}, computerId = '', autonomousEnv = 'prod') {
+ this.auth = auth ?? new AuthSessionManager(env.BACKEND_WS_URL.replace(/\/$/, '').replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'))
+ this.testToken = auth ? undefined : machineId
// `?label=<hostname>` lets the backend record which machine connected (shown on the machine card);
// `?computer=<stable id>` enforces one-computer-per-computer (a 2nd computer is rejected with HTTP 409);
// `?v=<VERSION>` is our own version, which the backend stores on the machine at every connect (the
// analytics report also carries it, but that path is opt-in, so this is the reliable one).
- const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}&v=${encodeURIComponent(VERSION)}`
+ const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}&v=${encodeURIComponent(VERSION)}&autonomousEnv=${encodeURIComponent(autonomousEnv)}`
this.url = computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base
this.onStatus = onStatus
- this.machineId = createHash('sha256').update(token).digest('hex').slice(0, 32)
+ this.machineId = machineId
this.e2ee = new E2eeManager({
machineId: this.machineId,
sendTo: (connId, frame) => this.sendTo(connId, frame),
@@ -410,9 +415,26 @@ export class BackendSocket {
}
connect(): void {
- if (this.closed || this.ws) return
- const ws = new WebSocket(this.url, [this.token])
+ if (this.closed || this.ws || this.connecting) return
+ this.connecting = true
+ void this.connectWithSession()
+ }
+
+ private async connectWithSession(): Promise<void> {
+ let token: string
+ try {
+ token = this.testToken ?? await this.auth.accessToken()
+ } catch (err) {
+ this.connecting = false
+ this.onStatus(false)
+ const delay = err instanceof AuthSessionError && err.code === 'INVALID_REFRESH' ? MAX_DELAY_MS : BASE_DELAY_MS
+ if (!this.closed) setTimeout(() => this.connect(), delay)
+ return
+ }
+ if (this.closed) { this.connecting = false; return }
+ const ws = new WebSocket(this.url, [token])
this.ws = ws
+ this.connecting = false
ws.on('open', () => {
this.attempts = 0
@@ -480,12 +502,18 @@ export class BackendSocket {
const msg = e.message || e.code || String(err)
console.error('[backend] socket error:', msg)
// 401/403 on the upgrade = this machine is gone/invalid (deleted while we were offline, or a bad
- // token). Retrying can't help → stop for good and let the CLI clear the saved token + shut down.
- if (/Unexpected server response: 40[13]\b/.test(msg)) {
+ // token). Retrying cannot help → stop for good and let CLI clear the saved SSO session.
+ if (/Unexpected server response: 401\b/.test(msg) && !this.retryingAuth) {
+ this.retryingAuth = true
+ this.ws = null
+ void this.auth.accessToken({ force: true, failedToken: token })
+ .then(() => { this.retryingAuth = false; this.connect() })
+ .catch(() => { this.retryingAuth = false; this.closed = true; this.onRevoked?.() })
+ } else if (/Unexpected server response: 40[13]\b/.test(msg)) {
this.closed = true
this.onRevoked?.()
}
- // 409 = one machine per machine: another computer already holds this machine. Keep the token; stop
+ // 409 = another computer already holds this machine. Keep the SSO session; stop
// retrying (the 40[13] regex above deliberately excludes 409, so without this it would loop).
else if (/Unexpected server response: 409\b/.test(msg)) {
this.closed = true
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 4fb3dd6e8..d86d3666f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2,12 +2,12 @@
/**
* machine-adapter CLI (the `harness` command) — connect this computer to a "remote" agent.
*
- * Terminology: the MACHINE *joins* a machine (`join <token>` → saved apiKey); a BROWSER
+ * Terminology: the MACHINE signs in with SSO (`harness login` → durable session); a BROWSER
* *pairs* with the computer for end-to-end encryption (`pair`/`unpair`/`pairings`, code + fingerprint).
* Keeping "pair" for the browser relationship only avoids overloading the word across two trust relations.
*
- * harness join <token> connect this computer to an existing remote machine. Later `harness join`
- * reconnects with the saved credential. `adapter unjoin` leaves + clears it.
+ * harness login opens native loopback SSO and saves this computer's session.
+ * harness start refreshes that session, resolves the machine, and starts the adapter.
*
* What runs: engine hooks/plugins (session metadata → localhost hook server → process registry),
* transcript/store readers, tmux process discovery,
@@ -19,7 +19,7 @@ import { readFileSync, writeFileSync, mkdirSync, openSync, existsSync, rmSync, s
import { join, resolve } from 'path'
import { fileURLToPath } from 'url'
import { spawn } from 'child_process'
-import { createHash } from 'crypto'
+import { createServer } from 'http'
import { homedir, hostname } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
@@ -28,10 +28,10 @@ import { ensureUtf8Locale } from './lib/childLocale.js'
import { binaryOnPath } from './lib/binaryOnPath.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
-import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
+import { PID_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { flashCommand } from './lib/flash.js'
import { readOrMintComputerId } from './lib/computerIdentity.js'
-import { startDeviceAuth, awaitApproval, type DeviceAuthStart } from './lib/deviceAuth.js'
+import { AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
import { buildEngineLaunchArgv } from './lib/engineLaunch.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
@@ -141,7 +141,7 @@ const LOG_FILE = join(env.ADAPTER_DATA_DIR, 'harness.log')
// opens this file. Two mechanisms, one ancestor each, in the right order.
const LEGACY_LOG_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.log')
// NOT under ADAPTER_DATA_DIR — see config/env.ts. `reset` wipes that dir, so an id kept there
-// regenerates and the next `harness auth device` mints a SECOND machine for a box that already has one.
+// regenerates and the next `harness login` mints a SECOND machine for a box that already has one.
const COMPUTER_ID_FILE = env.ADAPTER_COMPUTER_ID_FILE
// The machine's display name, mirrored from the backend (`machine_meta` on connect + web renames) by the
// daemon so the separate `harness status` process can print it. Absent = unnamed machine.
@@ -168,21 +168,21 @@ const REPAIR_RETRY_MS = 60_000
* then settle into the slow rhythm for processes that will never resolve. */
const REPAIR_EAGER_ATTEMPTS = 24 // ≈2 min at the 5s sweep
-function usage(): never {
+function usage(exitCode = 0): never {
console.log(`harness v${VERSION} — connect this computer to your machine
-Agents — after "harness join", run the vendor CLI directly inside tmux. Harness discovers supported
+Agents — after "harness start", run the vendor CLI directly inside tmux. Harness discovers supported
top-level processes automatically; it does not launch them or change their permission flags:
${ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}
A launcher that hands the pane to one of these works the same — "ori claude" is a Claude Code agent.
Machine:
- harness auth device connect this computer by approving a code in your browser (no token to copy)
- harness join <token> connect this computer to an existing machine using the token from its machine page
- harness join reconnect with the saved credential
- harness join -f run in the FOREGROUND (for a supervisor; logs to stdout)
- harness unjoin leave the machine (removes it on the web too) + clear the saved credential
- harness stop stop the background adapter (keeps the credential)
+ harness login sign in with SSO and save this computer's session
+ harness login --force stop the daemon and sign in with a different SSO account
+ harness start start the adapter using the saved SSO session
+ harness start -f run the adapter in the FOREGROUND (for a supervisor; logs to stdout)
+ harness logout stop the adapter and clear this computer's SSO session
+ harness stop stop the background adapter (keeps the SSO session)
harness reset stop the adapter and clear local CLI state
harness status show whether it's running (+ version)
harness version print the installed version (v${VERSION})
@@ -200,18 +200,13 @@ Browser end-to-end encryption:
harness --help
This computer's id lives at ${tildify(env.ADAPTER_COMPUTER_ID_FILE)} and is created once. Nothing here
-regenerates it — that is what keeps "harness auth device" reconnecting to the same machine instead of
+regenerates it — that is what keeps "harness start" reconnecting to the same machine instead of
making a new one. Deleting it (or ~/.harness) makes this look like a brand-new computer. On a box with
no durable home, a container or CI job, pin ADAPTER_COMPUTER_ID instead.
Env: BACKEND_WS_URL (${env.BACKEND_WS_URL}), WEB_URL (${env.WEB_URL}), ADAPTER_DATA_DIR,
ADAPTER_COMPUTER_ID, CLAUDE_PROJECTS_DIR, PORT`)
- process.exit(0)
-}
-
-/** agentId = sha256(token)[:32] — same derivation as the backend (agentIdFromKey). */
-function agentIdFromToken(token: string): string {
- return createHash('sha256').update(token).digest('hex').slice(0, 32)
+ process.exit(exitCode)
}
/** Compact a home-relative path with `~` for display. */
@@ -223,33 +218,14 @@ function tildify(p: string): string {
/** The currently-running script — dist/cli.js when built, src/cli.ts under tsx. */
const SCRIPT_PATH = fileURLToPath(import.meta.url)
-// The saved credential IS the agent apiKey — 32 random bytes as hex (64 chars).
-const TOKEN_RE = /^[0-9a-f]{64}$/i
-
-/** The saved credential (env override, else the token file), or null if this computer hasn't joined. */
-function readSavedToken(): string | null {
- const fromEnv = env.ADAPTER_TOKEN
- if (fromEnv && TOKEN_RE.test(fromEnv)) return fromEnv
- try {
- const saved = readFileSync(TOKEN_FILE, 'utf-8').trim()
- if (saved && TOKEN_RE.test(saved)) return saved
- } catch { /* none */ }
- return null
-}
-
-function saveToken(token: string): void {
- mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
- writeFileSync(TOKEN_FILE, token + '\n', { mode: 0o600 })
-}
-
/** This computer's identity — see lib/computerIdentity.ts. Sent on connect so the backend can enforce
- * one machine per computer, and used by `harness auth device` to reconnect to the machine already
+ * one machine per computer, and used by `harness start` to reconnect to the machine already
* bound to this box instead of minting a second one. */
function computerId(): string {
return readOrMintComputerId(COMPUTER_ID_FILE, env.ADAPTER_COMPUTER_ID)
}
-// ── join ───────────────────────────────────────────────────────────────────────────────────────
+// ── login ──────────────────────────────────────────────────────────────────────────────────────
// The REST base for control endpoints, derived from the WS URL (wss→https, ws→http).
function backendHttpBase(): string {
return env.BACKEND_WS_URL.replace(/\/$/, '').replace(/^wss:/, 'https:').replace(/^ws:/, 'http:')
@@ -282,64 +258,95 @@ async function postJson<T>(path: string, body: unknown, headers: Record<string,
return json.data as T
}
-/**
- * `harness auth device` — connect this computer without ever handling a token.
- *
- * Prints a six-character code, the user approves it in a browser where they are already signed in, and
- * we poll until a machine key comes back. The server answers with the machine already bound to THIS
- * computer, or makes one if it has none — so re-running this on the same box reconnects it rather than
- * collecting machines. Nothing is purchased; connecting a computer is free.
- */
-async function authDeviceCommand(foreground: boolean, force: boolean): Promise<void> {
- const existing = readSavedToken()
- if (existing && !force) {
- console.log('\n This computer is already connected.')
- console.log(` machine ${webBase()}/machine/${agentIdFromToken(existing)}`)
- console.log('\n Run `harness join` to reconnect, or `harness auth device --force` to connect it')
- console.log(' to a different account.\n')
- process.exit(0)
- }
-
- let start: DeviceAuthStart
- try {
- start = await startDeviceAuth(backendHttpBase(), computerId(), hostname())
- } catch (e) {
- console.error(`\n ✗ Could not reach the backend: ${e instanceof Error ? e.message : e}\n`)
- process.exit(1)
- }
-
- const url = `${webBase()}/connect?code=${encodeURIComponent(start.userCode)}`
- console.log('\n Approve this computer in your browser:\n')
- console.log(` ${url}`)
- console.log(`\n code ${start.userCode}\n`)
- openInBrowser(url)
-
- // A heartbeat, because ten minutes of nothing reads as a hang.
- let waited = 0
- const outcome = await awaitApproval(backendHttpBase(), start.deviceCode, {
- intervalSec: start.interval,
- expiresInSec: start.expiresIn,
- onTick: () => {
- waited += Math.max(2, start.interval)
- if (waited % 30 === 0) console.log(` …waiting for approval (${waited}s)`)
- },
+/** Resolve the canonical machine for the durable computer id without ever using a machine API key. */
+async function resolveComputerMachine(): Promise<AuthSession> {
+ const current = readAuthSession()
+ if (!current) throw new Error('Not signed in. Run `harness login`.')
+ const auth = new AuthSessionManager(backendHttpBase())
+ const accessToken = await auth.accessToken()
+ const result = await postJson<{ machine?: { machineId?: string } }>('/api/machines/resolve-computer', {
+ computerId: current.computerId,
+ label: hostname(),
+ }, {
+ authorization: `Bearer ${accessToken}`,
+ 'x-autonomous-env': current.autonomousEnv,
})
+ const machineId = result.machine?.machineId
+ if (!machineId) throw new Error('Backend did not return a machine id for this computer')
+ // Refresh can atomically replace the session while this request is in flight. Always merge the
+ // machine id into the newest file so a stale caller never rolls its rotated refresh token back.
+ const latest = readAuthSession()
+ if (!latest) throw new Error('SSO session disappeared while resolving this computer')
+ const next = latest.machineId === machineId
+ ? latest
+ : { ...latest, machineId, updatedAt: Date.now() }
+ if (next !== latest) writeAuthSession(next)
+ return next
+}
- if (outcome.status === 'denied') {
- console.error(`\n ✗ That request was declined${outcome.error ? ` (${outcome.error})` : ''}.\n`)
- process.exit(1)
- }
- if (outcome.status === 'expired') {
- console.error('\n ✗ The code expired before it was approved. Run `harness auth device` again.\n')
- process.exit(1)
+async function loginCommand(foreground: boolean, force: boolean): Promise<void> {
+ if (foreground) throw new Error('`harness login` does not run the adapter. Use `harness start -f`.')
+ if (readAuthSession() && !force) {
+ await resolveComputerMachine()
+ console.log('\n ✓ Already signed in. Run `harness start` to connect this computer.\n')
+ return
}
-
- saveToken(outcome.apiKey)
- console.log('\n ✓ Connected.\n')
- // Same tail as `join <token>`: one command gets you a running daemon.
- if ((await launch(outcome.apiKey, foreground)) === 'deauth') {
- console.error('\n✗ The machine rejected that key straight away — try `harness auth device` again.\n')
- process.exit(1)
+ // A forced login may intentionally switch SSO accounts. The old daemon must not keep streaming
+ // under its existing socket while this process replaces the durable session.
+ if (force) await stopDaemonProcess()
+ const callback = createServer()
+ await new Promise<void>((resolve, reject) => {
+ callback.once('error', reject)
+ callback.listen(0, '127.0.0.1', () => resolve())
+ })
+ const address = callback.address()
+ if (!address || typeof address === 'string') throw new Error('Could not start the SSO callback server')
+ const redirectUri = `http://127.0.0.1:${address.port}/callback`
+ try {
+ const start = await postJson<{ authorizeUrl?: string; tx?: string }>('/api/auth/authorize-native', {
+ redirectUri,
+ autonomousEnv: env.AUTONOMOUS_ENV,
+ })
+ if (!start.authorizeUrl || !start.tx) throw new Error('Backend did not return an SSO authorize URL')
+ console.log('\n Sign in to Harness in your browser:\n')
+ console.log(` ${start.authorizeUrl}\n`)
+ openInBrowser(start.authorizeUrl)
+ const callbackResult = await new Promise<{ code: string; state: string }>((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('SSO login timed out')), 5 * 60_000)
+ callback.on('request', (req, res) => {
+ const url = new URL(req.url ?? '/', redirectUri)
+ const code = url.searchParams.get('code')
+ const state = url.searchParams.get('state')
+ const error = url.searchParams.get('error')
+ res.writeHead(error || !code || !state ? 400 : 200, { 'content-type': 'text/html; charset=utf-8' })
+ res.end(error || !code || !state
+ ? '<h1>Harness login failed</h1><p>You can close this window.</p>'
+ : '<h1>Harness login complete</h1><p>You can close this window and return to the terminal.</p>')
+ clearTimeout(timeout)
+ if (error) reject(new Error(`SSO login failed: ${error}`))
+ else if (code && state) resolve({ code, state })
+ })
+ })
+ const exchanged = await postJson<{ token?: string; refreshToken?: string; expiresIn?: number; autonomousEnv?: 'prod' | 'stag' }>('/api/auth/exchange', {
+ ...callbackResult,
+ tx: start.tx,
+ })
+ if (!exchanged.token) throw new Error('SSO exchange returned no access token')
+ const id = computerId()
+ const session: AuthSession = {
+ version: 1,
+ accessToken: exchanged.token,
+ ...(exchanged.refreshToken ? { refreshToken: exchanged.refreshToken } : {}),
+ ...(exchanged.expiresIn ? { expiresAt: Date.now() + exchanged.expiresIn * 1000 } : {}),
+ autonomousEnv: exchanged.autonomousEnv ?? env.AUTONOMOUS_ENV,
+ computerId: id,
+ updatedAt: Date.now(),
+ }
+ writeAuthSession(session)
+ await resolveComputerMachine()
+ console.log('\n ✓ Signed in. Run `harness start` to connect this computer.\n')
+ } finally {
+ await new Promise<void>((resolve) => callback.close(() => resolve()))
}
}
@@ -353,46 +360,22 @@ function openInBrowser(url: string): void {
} catch { /* ignore */ }
}
-/**
- * `harness join [token]` — the single connect command.
- * - `join <token>`: connect a machine to an existing machine using the token shown on its machine page.
- * - `join` (no token): reconnect with the saved credential. Fresh machines must pass a token.
- */
-async function joinCommand(foreground: boolean, argToken?: string): Promise<void> {
+/** Start the adapter from a saved SSO session. Missing credentials never open a browser implicitly. */
+async function startCommand(foreground: boolean): Promise<void> {
+ if (!readAuthSession()) {
+ console.error('\n ✗ Not signed in. Run: harness login\n')
+ process.exit(1)
+ }
// Update-before-connect: pull the newest bundle FIRST so a machine always reconnects on the latest
- // build. Staging swaps ~/.harness/cli/cli.js, and the daemon join spawns below (`node cli.js __run`)
+ // build. Staging swaps ~/.harness/cli/cli.js, and the daemon start spawns below (`node cli.js __run`)
// executes those fresh bytes. Skipped in the foreground (THIS process becomes the long-lived daemon
- // and self-updates on its own) and on a dev/repo build; never blocks the join if the check fails.
+ // and self-updates on its own) and on a dev/repo build; never blocks start if the check fails.
if (!foreground) {
const v = await stageLatestBundle((m) => console.log(m))
if (v) console.log(` ✓ updated to v${v} — connecting on the new build`)
}
- if (argToken) {
- if (!TOKEN_RE.test(argToken)) {
- console.error('Invalid token — expected the 64-char hex key shown on the machine page ("Connect this computer").')
- process.exit(1)
- }
- saveToken(argToken)
- // Explicit token = the user chose a SPECIFIC machine → on deauth do NOT create a new one; say so.
- if ((await launch(argToken, foreground)) === 'deauth') {
- console.error("\n✗ That token isn't valid for any machine (it may have been deleted).")
- console.error(' Copy the current token from the machine page, then run: harness join <token>')
- process.exit(1)
- }
- return
- }
- const token = readSavedToken()
- // Nothing saved: rather than telling the user to go find a token, run the grant that gets one. This
- // is the first-run path, so it is the one that should cost the fewest steps.
- if (!token) { await authDeviceCommand(foreground, false); return }
- // If the saved token was rejected (machine deleted/revoked → 401/403), launch wipes it and returns
- // 'deauth'; do not create a new machine from the CLI.
- if ((await launch(token, foreground)) === 'deauth') {
- console.error('\n✗ This computer is no longer connected to a valid machine.')
- console.error(' Reconnect with: harness auth device')
- console.error(' (or copy a fresh token from the machine page and run: harness join <token>)')
- process.exit(1)
- }
+ await resolveComputerMachine()
+ await launch(foreground)
}
/** Download + sha256-verify + canary the manifest's cli.js/notify.mjs, then atomically swap them into
@@ -410,7 +393,7 @@ async function downloadCanaryStage(entry: UpdateEntry, dir: string, log: (m: str
/** Fetch the manifest and, if a strictly-newer build exists, stage it (see downloadCanaryStage). Returns
* the staged version, or null when nothing was staged — already current, a dev/repo or update-disabled
- * build, or ANY fetch/verify/canary failure (all swallowed: an update hiccup must never block `join`). */
+ * build, or ANY fetch/verify/canary failure (all swallowed: an update hiccup must never block `start`). */
async function stageLatestBundle(log: (m: string) => void): Promise<string | null> {
if (SCRIPT_PATH.endsWith('.ts') || env.ADAPTER_UPDATE_DISABLE) return null // dev/repo run never touches the installed bundle
const dir = resolve(env.ADAPTER_CLI_DIR)
@@ -448,10 +431,9 @@ async function updateCommand(): Promise<void> {
const running = readPid()
const wasRunning = !!(running && isAlive(running))
const relaunch = async (): Promise<void> => {
- const t = readSavedToken()
- if (!t) { console.log(' (no saved credential — run `harness join <token>` to connect on the new build.)'); process.exit(0) }
+ if (!readAuthSession()) { console.log(' (not signed in — run `harness login`, then `harness start`.)'); process.exit(0) }
await new Promise((r) => setTimeout(r, 1000)) // grace for the backend to release the one-machine claim
- await launch(t, false) // spawns a fresh daemon on the new bytes, prints status, and exits
+ await launch(false) // spawns a fresh daemon on the new bytes, prints status, and exits
}
if (wasRunning) { console.log(' stopping the running adapter…'); await stopDaemonProcess() }
@@ -465,28 +447,18 @@ async function updateCommand(): Promise<void> {
}
console.log(` ✓ installed v${entry.version}`)
if (wasRunning) { await relaunch(); return }
- console.log(`✓ Updated to v${entry.version}. Run \`harness join <token>\` to connect.`)
+ console.log(`✓ Updated to v${entry.version}. Run \`harness start\` to connect.`)
process.exit(0)
}
-/** `adapter unjoin` — leave the machine: delete the binding on the backend (self-authorized by the
- * agent's own key) and clear local creds; stop the daemon if it's running. */
-async function unjoin(): Promise<void> {
- const token = readSavedToken()
- if (!token) { console.log('This computer has not joined (no saved credential).'); process.exit(0) }
- try {
- await postJson('/api/machines/leave', {}, { 'x-api-key': token })
- console.log('Left the machine on the backend.')
- } catch (e) {
- // Best-effort: even if the binding was already gone (or the backend is down), clear locally.
- console.warn(`(backend leave failed: ${e instanceof Error ? e.message : e} — clearing locally anyway)`)
- }
+/** Stop the local adapter and discard this computer's SSO session. */
+async function logout(): Promise<void> {
const pid = readPid()
if (pid && isAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch { /* ignore */ } }
rmSync(PID_FILE, { force: true })
- rmSync(TOKEN_FILE, { force: true })
+ clearAuthSession()
rmSync(MACHINE_NAME_FILE, { force: true })
- console.log('This computer left the machine. Copy a token from the machine page, then run `harness join <token>` to connect again.')
+ console.log('Signed out. Run `harness login`, then `harness start`, to reconnect this computer.')
process.exit(0)
}
@@ -521,7 +493,7 @@ async function statBirthMs(path: string): Promise<number> {
}
/** The daemon body: hooks + watcher + process discovery + backend socket. */
-async function runForeground(token: string): Promise<void> {
+async function runForeground(session: AuthSession): Promise<void> {
installTimestampedConsole() // daemon-only: every harness.log line gets a wall-clock timestamp
const startedAt = Date.now()
@@ -843,7 +815,8 @@ async function runForeground(token: string): Promise<void> {
let backendRef: BackendSocket | undefined
let fullReconcile: (announceDevice?: boolean) => Promise<void> = async () => {}
- const backend = new BackendSocket(token, (connected) => {
+ const auth = new AuthSessionManager(backendHttpBase())
+ const backend = new BackendSocket(session.machineId ?? session.computerId, auth, (connected) => {
if (!connected) return
const sessions = registry.active()
console.log(`[cli] connected · ${sessions.length} agent(s) registered`)
@@ -909,7 +882,7 @@ async function runForeground(token: string): Promise<void> {
* to show a preview on.
*/
const analytics = new AnalyticsCollector({
- token: () => readSavedToken(),
+ token: () => readAuthSession()?.accessToken ?? null,
enginesPresent: () => [...new Set(registry.list().map((entry) => entry.engine))],
collectorVersion: VERSION,
})
@@ -2105,6 +2078,7 @@ async function runForeground(token: string): Promise<void> {
// deliberately does NOT expose chat/transcripts — those live in the cloud web (WEB_URL/commander).
onStatus: () => ({
machineId: backend.machineId,
+ computerId: session.computerId,
version: VERSION,
localWs: {
path: LOCAL_WS_PATH,
@@ -2158,7 +2132,6 @@ async function runForeground(token: string): Promise<void> {
onStop: () => { setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50) }, // let the 200 flush first
})
const localWsServer = attachLocalWsServer(hookServer, {
- token,
machineId: backend.machineId,
backend,
})
@@ -2569,7 +2542,7 @@ async function runForeground(token: string): Promise<void> {
prepareLogFile(LOG_FILE, LEGACY_LOG_FILE) // before the fd + the sinceOffset below, so both see one size
const fd = openSync(LOG_FILE, 'a')
const c = spawn(process.execPath, [SCRIPT_PATH, '__run'], {
- detached: true, env: { ...process.env, ADAPTER_TOKEN: token, ...extraEnv }, stdio: ['ignore', fd, fd],
+ detached: true, env: { ...process.env, ...extraEnv }, stdio: ['ignore', fd, fd],
})
// A spawn failure (e.g. EMFILE) emits 'error' on the child; with no listener that is an
// uncaughtException. Catch it so a failed update-restart can't take the old daemon down.
@@ -2661,11 +2634,10 @@ async function runForeground(token: string): Promise<void> {
process.on('SIGTERM', () => void shutdown('SIGTERM'))
process.on('exit', () => { shutdownSummaryPool(); shutdownVoiceRouter() })
- // This machine was deleted/revoked (from the web, or a 401 on reconnect) → clear the saved credential
- // and shut down. The user reconnects by copying a fresh token from the machine page.
+ // A machine revocation or invalid SSO refresh ends this adapter session permanently.
backend.onRevoked = () => {
console.log('[cli] this computer was removed from the machine — clearing credentials and stopping')
- try { rmSync(TOKEN_FILE, { force: true }) } catch { /* ignore */ }
+ clearAuthSession()
void shutdown('revoked')
}
@@ -2715,9 +2687,9 @@ async function runningDaemonVersion(): Promise<string> {
// `status` is a definitive state — `launch` only prints this after "[backend] connected" (so it's
// "● connected", never a one-shot never-updating "connecting…"); `status` prints running/stopped.
function printInfoBlock(opts: {
- status: string; pid: number; token: string; sessions: number; version: string
+ status: string; pid: number; machineId?: string; sessions: number; version: string
}): void {
- const link = `${env.WEB_URL.replace(/\/$/, '')}/machine/${agentIdFromToken(opts.token)}`
+ const link = opts.machineId ? `${env.WEB_URL.replace(/\/$/, '')}/machine/${opts.machineId}` : env.WEB_URL
const row = (k: string, v: string): string => ` ${k.padEnd(10)} ${v}`
const rule = ' ' + '─'.repeat(37)
console.log('')
@@ -2807,14 +2779,14 @@ async function waitForReady(sinceOffset: number, timeoutMs = 8000): Promise<Read
// ── daemon start / stop / status ───────────────────────────────────────────────────────────────
-/** Daemonize (or run inline) + print the info block. Returns 'deauth' when the saved credential was
- * rejected (401/403) so the caller (`joinCommand`) can ask for a fresh token; otherwise it exits. */
-async function launch(token: string, foreground: boolean): Promise<'deauth' | void> {
- // Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline. A 401/403
- // there is handled by backendSocket.onRevoked (clears token + shuts down); no token prompt inline.
+/** Daemonize (or run inline) with the saved SSO session. */
+async function launch(foreground: boolean): Promise<void> {
+ const session = readAuthSession()
+ if (!session) throw new Error('Not signed in. Run `harness login`.')
+ // Foreground mode (supervisor) OR dev/tsx (can't cleanly spawn a .ts detached) → run inline.
if (foreground || SCRIPT_PATH.endsWith('.ts')) {
if (!foreground) console.log('[cli] dev mode — running in the foreground (Ctrl-C to stop)')
- await runForeground(token)
+ await runForeground(session)
return
}
@@ -2831,7 +2803,7 @@ async function launch(token: string, foreground: boolean): Promise<'deauth' | vo
const logFd = openSync(LOG_FILE, 'a')
const child = spawn(process.execPath, [SCRIPT_PATH, '__run'], {
detached: true,
- env: { ...process.env, ADAPTER_TOKEN: token },
+ env: { ...process.env },
stdio: ['ignore', logFd, logFd],
})
writeFileSync(PID_FILE, String(child.pid) + '\n')
@@ -2844,20 +2816,19 @@ async function launch(token: string, foreground: boolean): Promise<'deauth' | vo
if (ready.state === 'deauth') {
try { if (child.pid) process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }
rmSync(PID_FILE, { force: true })
- rmSync(TOKEN_FILE, { force: true })
- return 'deauth' // caller decides what to say (saved-token vs. explicit-token error)
+ clearAuthSession()
+ return
}
// BUSY (409): one machine per machine — this machine is already connected from another computer. The
// credential is valid, just in use elsewhere, so KEEP the token; stop the daemon and inform (not a
- // failure, not a retry loop). The user stops the other machine first, then runs `harness join` here.
+ // failure, not a retry loop). The user stops the other machine first, then runs `harness start` here.
if (ready.state === 'busy') {
try { if (child.pid) process.kill(child.pid, 'SIGTERM') } catch { /* ignore */ }
rmSync(PID_FILE, { force: true })
- // NB: TOKEN_FILE is intentionally NOT removed — the credential is valid.
console.log('\n ℹ This machine is already connected from another computer.')
console.log(' Only one machine per machine — stop the adapter on that machine first,')
- console.log(' then run `harness join` here again.')
+ console.log(' then run `harness start` here again.')
process.exit(0)
}
@@ -2874,14 +2845,14 @@ async function launch(token: string, foreground: boolean): Promise<'deauth' | vo
console.error(`\n✗ Could not connect to the backend: ${ready.detail}`)
console.error(` backend ${env.BACKEND_WS_URL}`)
console.error(` logs ${tildify(LOG_FILE)}`)
- console.error(' If this computer was removed from your machine, copy a fresh token and run: harness join <token>')
+ console.error(' If this computer was removed from your machine, run: harness login')
}
process.exit(1)
}
// Not connected YET, but transient (backend deploying / 5xx / slow / not up). The daemon is alive and
// retries with backoff — it will connect on its own — so leave it running and say so plainly (never a
- // meaningless one-shot "connecting…"). The user runs `harness join` once, not on a babysitting loop.
+ // meaningless one-shot "connecting…"). The user runs `harness start` once, not on a babysitting loop.
if (ready.state === 'unreachable') {
// Lead with the RUNNING state (+ pid), not the error — the daemon IS started and self-retrying, so
// seeing a pid / "harness stop" later isn't a surprise. This is not a failure; it reconnects itself.
@@ -2897,7 +2868,7 @@ async function launch(token: string, foreground: boolean): Promise<'deauth' | vo
printInfoBlock({
status: '● connected',
pid: child.pid ?? 0,
- token,
+ machineId: session.machineId,
sessions: registry.list().length,
version: await runningDaemonVersion(),
})
@@ -2942,7 +2913,7 @@ function clearAdapterState(): void {
// NOT 'computer-id' — it no longer lives here (config/env.ts keeps it at the product root,
// above everything this function reaches) and it must not be cleared anyway. A reset that
// changed this computer's identity would orphan its machine and mint a fresh one on the next
- // `harness auth device`, which is the opposite of "start over on the same box".
+ // `harness login`, which is the opposite of "start over on the same box".
'machine-name',
'registry.json',
'registry-boot',
@@ -2959,14 +2930,14 @@ function clearAdapterState(): void {
rmStateFiles(cliDir)
}
-/** `adapter reset` — stop the daemon and clear local state so the next join starts fresh. */
+/** Stop the daemon and clear local state so the next login starts fresh. */
async function resetCommand(): Promise<void> {
const r = await stopDaemonProcess()
clearAdapterState()
console.log(`\n ✓ Cleared local machine CLI state at ${tildify(env.ADAPTER_DATA_DIR)}.`)
if (r.pid) console.log(` Stopped adapter process ${r.pid}.`)
- if (env.ADAPTER_TOKEN) console.log(' Note: ADAPTER_TOKEN is still set in the environment and will override disk state.')
- console.log('\n Start again with: harness join <token>\n')
+ clearAuthSession()
+ console.log('\n Start again with: harness login, then harness start\n')
process.exit(0)
}
@@ -2980,7 +2951,7 @@ async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown):
res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined })
} catch {
console.error('\n ✗ The adapter is not running on this computer.')
- console.error(' Start it first: harness join\n')
+ console.error(' Start it first: harness start\n')
process.exit(1)
}
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>
@@ -3014,9 +2985,9 @@ async function pairCommand(code: string | undefined): Promise<void> {
/** `harness browser-link` — print a reusable 7-day browser setup link for the current machine. */
async function browserLinkCommand(): Promise<void> {
- const token = readSavedToken()
- if (!token) { console.error('\n ✗ This computer is not joined. Run: harness join <token>\n'); process.exit(1) }
- const agentId = agentIdFromToken(token)
+ const session = readAuthSession()
+ if (!session?.machineId) { console.error('\n ✗ This computer is not signed in. Run: harness login\n'); process.exit(1) }
+ const agentId = session.machineId
let url = ''
try {
const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/e2ee/setup-link`, {
@@ -3035,7 +3006,7 @@ async function browserLinkCommand(): Promise<void> {
console.log('\n Reusable browser setup link (valid for 7 days):\n')
console.log(` ${url}\n`)
console.log(' Anyone with this link can pair a browser until it expires. Keep it private.\n')
- if (!readPid()) console.log(' Start the adapter with `harness join` if the browser cannot connect.\n')
+ if (!readPid()) console.log(' Start the adapter with `harness start` if the browser cannot connect.\n')
process.exit(0)
}
@@ -3082,14 +3053,13 @@ async function unpairCommand(id: string | undefined, all: boolean): Promise<void
async function status(): Promise<void> {
const pid = readPid()
const alive = pid != null && isAlive(pid)
- let token = env.ADAPTER_TOKEN ?? ''
- if (!token) { try { token = readFileSync(TOKEN_FILE, 'utf-8').trim() } catch { /* none */ } }
- if (!token) { console.log('machine: not joined. Run: harness join <token>'); process.exit(0) }
+ const session = readAuthSession()
+ if (!session) { console.log('machine: not signed in. Run: harness login'); process.exit(0) }
registry.load()
printInfoBlock({
status: alive ? '● running' : '○ stopped',
pid: pid ?? 0,
- token,
+ machineId: session.machineId,
sessions: registry.list().length,
// A stopped daemon answers nothing, so this falls back to the local build — which is what will run.
version: alive ? await runningDaemonVersion() : VERSION,
@@ -3112,31 +3082,22 @@ const onError = (err: unknown): never => {
}
switch (cmd) {
- case 'auth':
- // `device` is the only grant there is; accepting a bare `harness auth` keeps the common case short
- // without closing the door on a second one later.
- if (args[0] && args[0] !== 'device') {
- console.error(`Unknown auth subcommand: ${args[0]}\nUsage: harness auth device`)
- process.exit(1)
- }
- authDeviceCommand(foreground, flags.includes('--force')).catch(onError)
+ case 'login':
+ loginCommand(foreground, flags.includes('--force')).catch(onError)
break
- case 'join':
- joinCommand(foreground, args[0]).catch(onError)
+ case 'logout':
+ logout().catch(onError)
break
- case 'unjoin':
- unjoin().catch(onError)
- break
- // `start` is superseded by `join` (saved reconnect / `join <token>`). Kept as a deprecated
- // alias so muscle memory / old scripts don't break — including the old `start <token>` form.
case 'start':
- console.error('(note: "harness start" is now "harness join")')
- joinCommand(foreground, args[0]).catch(onError)
+ startCommand(foreground).catch(onError)
break
- case '__run': { // internal: the detached daemon child runs the adapter inline (token via env)
- const t = readSavedToken()
- if (!t) onError(new Error('no credential for __run'))
- else runForeground(t).catch(onError)
+ case 'join':
+ console.error('`harness join` has been removed. Run `harness login`, then `harness start`.')
+ process.exit(1)
+ case '__run': { // internal: detached daemon child reads the durable SSO session
+ const session = readAuthSession()
+ if (!session) onError(new Error('no SSO session for __run'))
+ else runForeground(session).catch(onError)
break
}
case 'pair':
@@ -3196,5 +3157,5 @@ switch (cmd) {
break
default:
console.error(`Unknown command: ${cmd}`)
- usage()
+ usage(1)
}
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
new file mode 100644
index 000000000..0f63c99a6
--- /dev/null
+++ b/cli/src/cliCommand.spec.ts
@@ -0,0 +1,56 @@
+import { spawnSync } from 'child_process'
+import { mkdtempSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import { fileURLToPath } from 'url'
+import { afterEach, describe, expect, it } from 'vitest'
+
+const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))
+const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')
+const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
+const dirs: string[] = []
+
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+function run(...args: string[]) {
+ const root = mkdtempSync(join(tmpdir(), 'harness-cli-command-'))
+ dirs.push(root)
+ return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], {
+ cwd: CLI_ROOT,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ HOME: root,
+ HARNESS_AUTH_DIR: join(root, 'auth'),
+ ADAPTER_DATA_DIR: join(root, 'data'),
+ ADAPTER_CLI_DIR: join(root, 'cli'),
+ ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),
+ ADAPTER_UPDATE_DISABLE: 'true',
+ },
+ })
+}
+
+describe('CLI login/start command contract', () => {
+ it('does not start or open SSO when start has no saved session', () => {
+ const result = run('start')
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Not signed in. Run: harness login')
+ expect(result.stdout).not.toContain('Sign in to Harness in your browser')
+ })
+
+ it('rejects the removed join command with the two-step migration', () => {
+ const result = run('join')
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('`harness join` has been removed.')
+ expect(result.stderr).toContain('`harness login`, then `harness start`')
+ })
+
+ it('returns a nonzero status for an unknown command', () => {
+ const result = run('not-a-command')
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain('Unknown command: not-a-command')
+ })
+})
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 865f4f665..eee46a094 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -15,7 +15,8 @@ const adapterDataDir = join(adapterCliDir, 'data')
// dir: `harness reset` wipes that dir, the ~/.machine adoption below force-replaces entries in it, and
// a custom ADAPTER_DATA_DIR moves it. A computer's identity must outlive all three — the backend binds
// a machine to it, so a regenerated id silently mints a SECOND machine for a box that already had one.
-// Nothing in the CLI writes above `~/.harness/cli`, which is exactly why it sits here.
+// The SSO session is the only other product-root state (`~/.harness/auth/session.json`); both it and
+// this id intentionally survive an adapter-data reset.
const computerIdFile = join(adapterRootDir, 'computer-id')
// ── One-time adoption of adapter state written under an older name ────────────────────────────────
@@ -117,11 +118,10 @@ const envSchema = z.object({
PORT: z.string().default('18473').transform(Number),
// The backend the CLI dials (`/api/adapter-ws`). Local dev: ws://localhost:8090.
BACKEND_WS_URL: z.string().default('wss://harness-api.autonomous.ai'),
+ // SSO account plane used by native-loopback login and the adapter WebSocket.
+ AUTONOMOUS_ENV: z.enum(['prod', 'stag']).default('prod'),
// Web app base URL — used to print the agent's chat link on `adapter start`. Local: http://localhost:3000.
WEB_URL: z.string().default('https://harness.autonomous.ai'),
- // Connect token (the agent apiKey). Usually passed as `adapter start <token>` and persisted to
- // ${ADAPTER_DATA_DIR}/token; this env var overrides both.
- ADAPTER_TOKEN: z.string().optional(),
// Set to '1' to let the New Agent folder browser (fs_list_dir) list directories outside $HOME.
// Off by default so a fat-fingered path or a compromised relay hop can't walk the whole filesystem.
HARNESS_FS_BROWSE_UNRESTRICTED: z.string().optional(),
@@ -214,7 +214,7 @@ const envSchema = z.object({
DEVIN_CONFIG_PATH: z
.string()
.default(join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'devin', 'config.json')),
- // Where the tmux-session registry + connect token are persisted.
+ // Where the tmux-session registry and daemon-local state are persisted.
ADAPTER_DATA_DIR: z.string().default(adapterDataDir),
// This computer's stable id, minted once and never regenerated (see computerIdFile above). Pin it
// explicitly on a box with no durable home — a container or CI job that gets a fresh ~/.harness on
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 7ca3d7343..b6f5de870 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -1,7 +1,7 @@
# Adding an agent framework to Harness
**This is the CLI path.** Your agent is a command — run on a laptop, a server, a cloud VM, anywhere
-`harness join` runs — and Harness reads the transcript it writes. The code calls that an **engine**,
+`harness login` runs — and Harness reads the transcript it writes. The code calls that an **engine**,
and this directory holds one folder per engine. If your agent is a service reached over HTTP instead,
you want the API path — [`provider/`](../../../provider/README.md).
diff --git a/cli/src/engines/cursor/localE2e.spec.ts b/cli/src/engines/cursor/localE2e.spec.ts
index 3b2907fb3..29feca0c1 100644
--- a/cli/src/engines/cursor/localE2e.spec.ts
+++ b/cli/src/engines/cursor/localE2e.spec.ts
@@ -119,10 +119,10 @@ describe.skipIf(!runCursorE2e)('Cursor local HTTP/WS/tmux E2E', () => {
const temp = await mkdtemp(join(tmpdir(), 'machine-cursor-e2e-'))
const dataDir = join(temp, 'adapter-data')
+ const authDir = join(temp, 'auth')
const registryPath = join(dataDir, 'registry.json')
const tmuxSession = `machine-cursor-e2e-${process.pid}`
const hookPort = await freePort()
- const token = 'a'.repeat(64)
const frames: Envelope[] = []
const logs: string[] = []
const originalHooks = existsSync(cursorHooksPath) ? await readFile(cursorHooksPath) : null
@@ -142,12 +142,24 @@ describe.skipIf(!runCursorE2e)('Cursor local HTTP/WS/tmux E2E', () => {
let adapter: ChildProcess | null = null
try {
await installTemporaryCursorHooks(hookPort, dataDir)
+ await mkdir(authDir, { recursive: true, mode: 0o700 })
+ await writeFile(join(authDir, 'session.json'), JSON.stringify({
+ version: 1,
+ accessToken: 'test-access-token',
+ refreshToken: 'test-refresh-token',
+ expiresAt: Date.now() + 3_600_000,
+ autonomousEnv: 'prod',
+ computerId: 'cursor-e2e-computer',
+ machineId: 'cursor-e2e-machine',
+ updatedAt: Date.now(),
+ }) + '\n', { mode: 0o600 })
adapter = spawn(tsxBin, ['src/cli.ts', '__run'], {
cwd: adapterRoot,
env: {
...process.env,
NODE_ENV: 'test',
- ADAPTER_TOKEN: token,
+ HARNESS_AUTH_DIR: authDir,
+ ADAPTER_COMPUTER_ID: 'cursor-e2e-computer',
ADAPTER_DATA_DIR: dataDir,
BACKEND_WS_URL: `ws://127.0.0.1:${address.port}`,
WEB_URL: 'http://127.0.0.1:3000',
diff --git a/cli/src/lib/analytics/collector.ts b/cli/src/lib/analytics/collector.ts
index 7a61ba660..89d2e8823 100644
--- a/cli/src/lib/analytics/collector.ts
+++ b/cli/src/lib/analytics/collector.ts
@@ -14,7 +14,7 @@
* - **Collection starts immediately; uploading waits for acknowledgement.** Aggregates are
* snapshots, so holding them costs nothing and loses nothing. That is what lets the product be on
* by default while still being able to say, truthfully, that no byte left this computer before
- * its owner read the field list. The CLI runs headless on servers and under `harness join`, where
+ * its owner read the field list. The CLI runs headless on servers and under `harness login`, where
* there is no screen to show a preview on, so the hold is the only honest mechanism available.
* - **The upload response is the control channel.** A daemon has no other way to learn the owner
* turned collection off or deleted the history.
diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.ts
new file mode 100644
index 000000000..ddca64364
--- /dev/null
+++ b/cli/src/lib/authSession.spec.ts
@@ -0,0 +1,75 @@
+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtemp, readFile, rm } from 'fs/promises'
+import { tmpdir } from 'os'
+
+const authDir = await mkdtemp(`${tmpdir()}/harness-auth-session-`)
+process.env.HARNESS_AUTH_DIR = authDir
+
+const {
+ AUTH_SESSION_FILE,
+ AuthSessionError,
+ AuthSessionManager,
+ clearAuthSession,
+ readAuthSession,
+ writeAuthSession,
+} = await import('./authSession.js')
+
+const baseSession = () => ({
+ version: 1 as const,
+ accessToken: 'old-access',
+ refreshToken: 'refresh-1',
+ expiresAt: Date.now() - 1,
+ autonomousEnv: 'prod' as const,
+ computerId: 'computer-1',
+ machineId: 'machine-1',
+ updatedAt: Date.now(),
+})
+
+afterEach(() => {
+ clearAuthSession()
+ vi.unstubAllGlobals()
+})
+
+afterAll(async () => {
+ delete process.env.HARNESS_AUTH_DIR
+ await rm(authDir, { recursive: true, force: true })
+})
+
+describe('AuthSessionManager', () => {
+ it('coalesces concurrent expired-token refreshes into one request and persists the rotated tokens', async () => {
+ writeAuthSession(baseSession())
+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ data: { token: 'new-access', refreshToken: 'refresh-2', expiresIn: 3600 },
+ })))
+ vi.stubGlobal('fetch', fetchMock)
+ const manager = new AuthSessionManager('https://api.example.test')
+
+ await expect(Promise.all([manager.accessToken(), manager.accessToken()])).resolves.toEqual(['new-access', 'new-access'])
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(readAuthSession()).toMatchObject({ accessToken: 'new-access', refreshToken: 'refresh-2' })
+ await expect(readFile(AUTH_SESSION_FILE, 'utf8')).resolves.toContain('new-access')
+ })
+
+ it('uses the newer persisted access token rather than refreshing a stale 401 again', async () => {
+ writeAuthSession({ ...baseSession(), accessToken: 'already-refreshed', expiresAt: Date.now() + 3_600_000 })
+ const fetchMock = vi.fn<typeof fetch>()
+ vi.stubGlobal('fetch', fetchMock)
+ const manager = new AuthSessionManager('https://api.example.test')
+
+ await expect(manager.accessToken({ force: true, failedToken: 'old-access' })).resolves.toBe('already-refreshed')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('clears an invalid refresh session instead of retrying it forever', async () => {
+ writeAuthSession(baseSession())
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({
+ success: false,
+ error: { code: 'REFRESH_TOKEN_INVALID', message: 'expired' },
+ }), { status: 401 })))
+ const manager = new AuthSessionManager('https://api.example.test')
+
+ await expect(manager.accessToken()).rejects.toMatchObject({ name: AuthSessionError.name, code: 'INVALID_REFRESH' })
+ expect(readAuthSession()).toBeNull()
+ })
+})
diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.ts
new file mode 100644
index 000000000..e6228702d
--- /dev/null
+++ b/cli/src/lib/authSession.ts
@@ -0,0 +1,189 @@
+import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
+import { homedir } from 'os'
+import { join } from 'path'
+
+export interface AuthSession {
+ version: 1
+ accessToken: string
+ refreshToken?: string
+ expiresAt?: number
+ autonomousEnv: 'prod' | 'stag'
+ computerId: string
+ machineId?: string
+ updatedAt: number
+}
+
+export class AuthSessionError extends Error {
+ constructor(message: string, readonly code: 'MISSING' | 'INVALID_REFRESH' | 'UNAVAILABLE') {
+ super(message)
+ this.name = 'AuthSessionError'
+ }
+}
+
+// HARNESS_AUTH_DIR exists for isolated test processes. Product installs always use ~/.harness/auth.
+export const AUTH_DIR = process.env.HARNESS_AUTH_DIR?.trim() || join(homedir(), '.harness', 'auth')
+export const AUTH_SESSION_FILE = join(AUTH_DIR, 'session.json')
+const LOCK_FILE = join(AUTH_DIR, 'session.lock')
+const LOCK_STALE_MS = 30_000
+const REFRESH_SKEW_MS = 60_000
+
+function parse(raw: string): AuthSession | null {
+ try {
+ const value = JSON.parse(raw) as Partial<AuthSession>
+ if (value.version !== 1 || typeof value.accessToken !== 'string' || !value.accessToken ||
+ typeof value.computerId !== 'string' || !value.computerId ||
+ (value.autonomousEnv !== 'prod' && value.autonomousEnv !== 'stag')) return null
+ return {
+ version: 1,
+ accessToken: value.accessToken,
+ ...(typeof value.refreshToken === 'string' && value.refreshToken ? { refreshToken: value.refreshToken } : {}),
+ ...(typeof value.expiresAt === 'number' && Number.isFinite(value.expiresAt) ? { expiresAt: value.expiresAt } : {}),
+ autonomousEnv: value.autonomousEnv,
+ computerId: value.computerId,
+ ...(typeof value.machineId === 'string' && value.machineId ? { machineId: value.machineId } : {}),
+ updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
+ }
+ } catch { return null }
+}
+
+export function readAuthSession(): AuthSession | null {
+ try { return parse(readFileSync(AUTH_SESSION_FILE, 'utf8')) } catch { return null }
+}
+
+export function hasAuthSession(): boolean { return readAuthSession() !== null }
+
+function ensureDir(): void {
+ mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 })
+ try { chmodSync(AUTH_DIR, 0o700) } catch { /* best effort on non-POSIX */ }
+}
+
+export function writeAuthSession(session: AuthSession): void {
+ ensureDir()
+ const temp = join(AUTH_DIR, `.session.${process.pid}.${Date.now()}.tmp`)
+ try {
+ writeFileSync(temp, JSON.stringify(session) + '\n', { mode: 0o600 })
+ try { chmodSync(temp, 0o600) } catch { /* best effort on non-POSIX */ }
+ renameSync(temp, AUTH_SESSION_FILE)
+ try { chmodSync(AUTH_SESSION_FILE, 0o600) } catch { /* best effort on non-POSIX */ }
+ } finally {
+ try { rmSync(temp, { force: true }) } catch { /* ignore */ }
+ }
+}
+
+export function clearAuthSession(): void {
+ try { rmSync(AUTH_SESSION_FILE, { force: true }) } catch { /* ignore */ }
+}
+
+async function withLock<T>(action: () => Promise<T>): Promise<T> {
+ ensureDir()
+ let deadline = Date.now() + LOCK_STALE_MS
+ let reclaimedStaleLock = false
+ while (true) {
+ let fd: number
+ try {
+ fd = openSync(LOCK_FILE, 'wx', 0o600)
+ } catch {
+ if (Date.now() >= deadline) {
+ let removed = false
+ try {
+ const age = Date.now() - statSync(LOCK_FILE).mtimeMs
+ if (age >= LOCK_STALE_MS) {
+ rmSync(LOCK_FILE, { force: true })
+ removed = true
+ }
+ } catch { /* lock disappeared or is unreadable */ }
+ if (removed && !reclaimedStaleLock) {
+ reclaimedStaleLock = true
+ deadline = Date.now() + LOCK_STALE_MS
+ continue
+ }
+ throw new AuthSessionError('Another Harness process is refreshing SSO credentials. Please retry.', 'UNAVAILABLE')
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve, 40))
+ continue
+ }
+ try {
+ return await action()
+ } finally {
+ closeSync(fd)
+ try { rmSync(LOCK_FILE, { force: true }) } catch { /* ignore */ }
+ }
+ }
+}
+
+type RefreshResult = { token: string; refreshToken?: string; expiresIn?: number }
+
+async function refreshRequest(baseUrl: string, current: AuthSession): Promise<RefreshResult> {
+ if (!current.refreshToken) throw new AuthSessionError('No SSO refresh token. Run `harness login`.', 'MISSING')
+ let response: Response
+ try {
+ response = await fetch(`${baseUrl.replace(/\/$/, '')}/api/auth/refresh`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ refreshToken: current.refreshToken, autonomousEnv: current.autonomousEnv }),
+ })
+ } catch {
+ throw new AuthSessionError('SSO refresh service is unavailable.', 'UNAVAILABLE')
+ }
+ const body = await response.json().catch(() => ({})) as {
+ success?: boolean; data?: { token?: unknown; refreshToken?: unknown; expiresIn?: unknown }; error?: { code?: unknown; message?: unknown }
+ }
+ if (response.status === 401 || body.error?.code === 'REFRESH_TOKEN_INVALID') {
+ throw new AuthSessionError('SSO refresh token is invalid. Run `harness login`.', 'INVALID_REFRESH')
+ }
+ if (!response.ok || body.success === false || typeof body.data?.token !== 'string' || !body.data.token) {
+ throw new AuthSessionError(typeof body.error?.message === 'string' ? body.error.message : 'SSO refresh service is unavailable.', 'UNAVAILABLE')
+ }
+ return {
+ token: body.data.token,
+ ...(typeof body.data.refreshToken === 'string' && body.data.refreshToken ? { refreshToken: body.data.refreshToken } : {}),
+ ...(typeof body.data.expiresIn === 'number' && body.data.expiresIn > 0 ? { expiresIn: body.data.expiresIn } : {}),
+ }
+}
+
+/** One in-process refresh plus a file lock for daemon/command races. */
+export class AuthSessionManager {
+ private refreshInFlight: Promise<string> | null = null
+ constructor(private readonly backendBaseUrl: string) {}
+
+ session(): AuthSession | null { return readAuthSession() }
+
+ async accessToken(opts: { force?: boolean; failedToken?: string } = {}): Promise<string> {
+ const current = readAuthSession()
+ if (!current) throw new AuthSessionError('Not signed in. Run `harness login`.', 'MISSING')
+ if (opts.failedToken && current.accessToken !== opts.failedToken) return current.accessToken
+ const needsRefresh = opts.force === true || (current.expiresAt != null && current.expiresAt <= Date.now() + REFRESH_SKEW_MS)
+ if (!needsRefresh) return current.accessToken
+ if (this.refreshInFlight) return this.refreshInFlight
+ const running = withLock(async () => {
+ const latest = readAuthSession()
+ if (!latest) throw new AuthSessionError('Not signed in. Run `harness login`.', 'MISSING')
+ if (opts.failedToken && latest.accessToken !== opts.failedToken) return latest.accessToken
+ const stillNeedsRefresh = opts.force === true || (latest.expiresAt != null && latest.expiresAt <= Date.now() + REFRESH_SKEW_MS)
+ if (!stillNeedsRefresh) return latest.accessToken
+ try {
+ const refreshed = await refreshRequest(this.backendBaseUrl, latest)
+ const next: AuthSession = {
+ ...latest,
+ accessToken: refreshed.token,
+ ...(refreshed.refreshToken ? { refreshToken: refreshed.refreshToken } : {}),
+ ...(refreshed.expiresIn ? { expiresAt: Date.now() + refreshed.expiresIn * 1000 } : {}),
+ updatedAt: Date.now(),
+ }
+ writeAuthSession(next)
+ return next.accessToken
+ } catch (err) {
+ if (err instanceof AuthSessionError && err.code === 'INVALID_REFRESH') clearAuthSession()
+ throw err
+ }
+ })
+ this.refreshInFlight = running
+ try { return await running } finally { if (this.refreshInFlight === running) this.refreshInFlight = null }
+ }
+
+ updateMachineId(machineId: string): void {
+ const current = readAuthSession()
+ if (!current || current.machineId === machineId) return
+ writeAuthSession({ ...current, machineId, updatedAt: Date.now() })
+ }
+}
diff --git a/cli/src/lib/computerIdentity.ts b/cli/src/lib/computerIdentity.ts
index 9a4870ea0..87a5ee174 100644
--- a/cli/src/lib/computerIdentity.ts
+++ b/cli/src/lib/computerIdentity.ts
@@ -5,7 +5,7 @@ import { randomUUID } from 'crypto'
/**
* This computer's identity: minted ONCE, then never regenerated.
*
- * The backend BINDS a machine to this value — `harness auth device` reuses the machine already bound
+ * The backend BINDS a machine to this value — `harness login` reuses the machine already bound
* to it, and creates one only when there is none. So regenerating it is not a cosmetic reset: it
* orphans the machine this box was using and mints a replacement. Every path here is therefore
* write-once, and the file itself lives at the product root (`~/.harness/computer-id`), above
diff --git a/cli/src/lib/daemonState.ts b/cli/src/lib/daemonState.ts
index 22671dde9..deef912c7 100644
--- a/cli/src/lib/daemonState.ts
+++ b/cli/src/lib/daemonState.ts
@@ -6,16 +6,13 @@
* which would execute the command dispatcher.
*/
-import { existsSync, readFileSync } from 'fs'
+import { readFileSync } from 'fs'
import { join } from 'path'
import { env } from '../config/env.js'
+import { hasAuthSession } from './authSession.js'
-export const TOKEN_FILE = join(env.ADAPTER_DATA_DIR, 'token')
export const PID_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.pid')
-// The saved credential IS the agent apiKey — 32 random bytes as hex (64 chars).
-const TOKEN_RE = /^[0-9a-f]{64}$/i
-
/** The daemon's localhost control port — FIXED at env.PORT (no fallback), so pair/status/stop always
* reach it and a leftover is findable with `lsof :<PORT>`. */
export function daemonPort(): number {
@@ -33,14 +30,8 @@ export function isAlive(pid: number): boolean {
try { process.kill(pid, 0); return true } catch { return false }
}
-/** Has this computer ever joined? (env override, else a well-formed token file.) Deliberately returns a
- * boolean, not the token — callers here only need to pick the right "how to fix it" message. */
-export function hasSavedToken(): boolean {
- const fromEnv = env.ADAPTER_TOKEN
- if (fromEnv && TOKEN_RE.test(fromEnv.trim())) return true
- if (!existsSync(TOKEN_FILE)) return false
- try { return TOKEN_RE.test(readFileSync(TOKEN_FILE, 'utf-8').trim()) } catch { return false }
-}
+/** Whether a durable SSO session exists for this computer. */
+export function hasSavedAuthSession(): boolean { return hasAuthSession() }
/** Is the background daemon process alive right now? (pid file present AND that pid still exists) */
export function isDaemonRunning(): boolean {
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index ada444284..72e7a5269 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -146,7 +146,7 @@ export function installCodexHooks(port: number): void {
settings = JSON.parse(readFileSync(CODEX_HOOKS_PATH, 'utf-8')) as Settings
} catch (err) {
console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${CODEX_HOOKS_PATH}`)
- console.error('[hooks] fix the file, then restart harness join')
+ console.error('[hooks] fix the file, then restart harness login')
return
}
}
@@ -194,7 +194,7 @@ export function installGrokHooks(port: number): void {
settings = JSON.parse(readFileSync(GROK_HOOKS_PATH, 'utf-8')) as Settings
} catch {
console.error(`[hooks] Grok hooks file is invalid JSON; leaving it unchanged: ${GROK_HOOKS_PATH}`)
- console.error('[hooks] fix the file, then restart harness join')
+ console.error('[hooks] fix the file, then restart harness login')
return
}
}
@@ -252,7 +252,7 @@ export function installAgyHooks(port: number): void {
file = JSON.parse(readFileSync(AGY_HOOKS_PATH, 'utf-8')) as AgyHookFile
} catch {
console.error(`[hooks] agy hooks file is invalid JSON; leaving it unchanged: ${AGY_HOOKS_PATH}`)
- console.error('[hooks] fix the file, then restart harness join')
+ console.error('[hooks] fix the file, then restart harness login')
return
}
}
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 13426c902..2c59540f7 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -6,7 +6,6 @@ import type { Frame, LocalClientSink } from './backendSocket.js'
import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer } from './localWsServer.js'
import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
-const token = 'machine-api-key'
const machineId = 'machine-123'
const streamId = '00112233-4455-6677-8899-aabbccddeeff'
@@ -62,16 +61,16 @@ describe('local CLI WebSocket', () => {
async function start(backend: FakeBackend): Promise<string> {
server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
- local = attachLocalWsServer(server, { token, machineId, backend })
+ local = attachLocalWsServer(server, { machineId, backend })
await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
const port = (server.address() as AddressInfo).port
return `ws://127.0.0.1:${port}/api/local-ws`
}
- it('authenticates, selects the exact machine, and routes JSON plus HTRL binary', async () => {
+ it('accepts loopback, selects the exact machine, and routes JSON plus HTRL binary', async () => {
const backend = new FakeBackend()
const url = await start(backend)
- const ws = new WebSocket(url, [token])
+ const ws = new WebSocket(url)
await onceOpen(ws)
const connected = onceMessage(ws)
ws.send(JSON.stringify({
@@ -106,20 +105,20 @@ describe('local CLI WebSocket', () => {
ws.close()
})
- it('rejects the wrong API key before WebSocket upgrade', async () => {
+ it('does not require a credential on the loopback transport', async () => {
const url = await start(new FakeBackend())
- const ws = new WebSocket(url, ['wrong-key'])
- const error = await new Promise<Error>((resolve) => ws.once('error', resolve))
- expect(error.message).toContain('401')
+ const ws = new WebSocket(url, ['legacy-client-label'])
+ await onceOpen(ws)
+ ws.close()
})
it('rejects browser origins and machine-id mismatches', async () => {
const url = await start(new FakeBackend())
- const browser = new WebSocket(url, [token], { origin: 'https://example.com' })
+ const browser = new WebSocket(url, { origin: 'https://example.com' })
const error = await new Promise<Error>((resolve) => browser.once('error', resolve))
expect(error.message).toContain('403')
- const ws = new WebSocket(url, [token])
+ const ws = new WebSocket(url)
await onceOpen(ws)
const closed = new Promise<number>((resolve) => ws.once('close', resolve))
ws.send(JSON.stringify({
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index a37f81d3c..11b7f1097 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -1,4 +1,4 @@
-import { randomUUID, timingSafeEqual } from 'node:crypto'
+import { randomUUID } from 'node:crypto'
import type http from 'node:http'
import type { Socket } from 'node:net'
import { WebSocket, WebSocketServer, type RawData } from 'ws'
@@ -19,7 +19,6 @@ export interface LocalWsBackend {
}
export interface LocalWsServerOptions {
- token: string
machineId: string
backend: LocalWsBackend
}
@@ -32,17 +31,6 @@ function isLoopback(address: string | undefined): boolean {
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
}
-function secureEqual(left: string, right: string): boolean {
- const a = Buffer.from(left)
- const b = Buffer.from(right)
- return a.length === b.length && timingSafeEqual(a, b)
-}
-
-function offeredProtocols(value: string | string[] | undefined): string[] {
- const raw = Array.isArray(value) ? value.join(',') : value ?? ''
- return raw.split(',').map((part) => part.trim()).filter(Boolean)
-}
-
function rejectUpgrade(socket: Socket, status: number, reason: string): void {
if (socket.destroyed) return
socket.end(
@@ -80,15 +68,17 @@ function binaryBytes(raw: RawData): Uint8Array {
}
/**
- * Add an authenticated loopback WebSocket endpoint to the CLI's existing HTTP server.
- * The machine API key is accepted only as a WebSocket subprotocol and is never returned by /api/status.
+ * Add an internal loopback WebSocket endpoint to the CLI's existing HTTP server. It intentionally has
+ * no credential: loopback-only, no Origin header, and the desktop computer-id validation identify the
+ * local process without placing SSO credentials on this transport.
*/
export function attachLocalWsServer(server: http.Server, options: LocalWsServerOptions): LocalWsServer {
const wss = new WebSocketServer({
noServer: true,
maxPayload: MAX_JSON_BYTES,
- handleProtocols: (protocols) =>
- [...protocols].find((protocol) => secureEqual(protocol, options.token)) ?? false,
+ // The loopback endpoint deliberately has no credential. Echo a protocol only for generic WS
+ // clients that insist on proposing one; it carries no authority and is never inspected.
+ handleProtocols: (protocols) => [...protocols][0] ?? false,
})
const onUpgrade = (req: http.IncomingMessage, socket: Socket, head: Buffer): void => {
@@ -102,11 +92,6 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
rejectUpgrade(socket, 403, 'Forbidden')
return
}
- const protocols = offeredProtocols(req.headers['sec-websocket-protocol'])
- if (!protocols.some((protocol) => secureEqual(protocol, options.token))) {
- rejectUpgrade(socket, 401, 'Unauthorized')
- return
- }
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))
}
server.on('upgrade', onUpgrade)