Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

feat(computers): rotate workspace pairing code

bingqilinweimaotai5b5bcf4ff0f8
diff --git a/docs/BYOA.md b/docs/BYOA.md
index 1256cdb..8b85ea9 100644
--- a/docs/BYOA.md
+++ b/docs/BYOA.md
@@ -498,17 +498,19 @@ CREATE TABLE computers (
Every company gets a `kind='cloud'` "Cumora Cloud" row; `computers.kind`
is what the scheduler branches on. Companies also hold a persistent
-pairing token (`companies.pair_token`) shown in the Add-Computer UI.
+workspace pairing code (`companies.pair_token`) shown in the Add-Computer UI.
+Each paired computer has a separate reconnect code (`computers.pair_token`).
---
## Auth & pairing
A Computer is a **registered device** with its own revocable credential —
-not the user's session. "Remove Computer" is a real kill switch.
+not the user's session. "Remove Computer" is a real kill switch for that
+device; it does not rotate the workspace pairing code.
```
-1. UI "Add Computer" ─► the company's persistent pairing token
+1. UI "Add Computer" ─► the company's persistent workspace pairing code
2. user runs: npx cumora agent computer --pair <code> --server <url>
3. daemon ─► POST /api/computers/pair { code, hostName, engines, version, supervised }
◄── { computerId, deviceToken } (stored in ~/.cumora/computer.json;
@@ -519,18 +521,58 @@ not the user's session. "Remove Computer" is a real kill switch.
used for that agent's wake-stream SSE and daemon-side `/runtime/cli` calls.
5. heartbeat: POST /api/computers/heartbeat every 30s; a computer with no
heartbeat for 90s shows offline and its agents show sleeping.
-6. UI "Remove" ─► sets revoked_at; the device token and all derived agent
- JWTs are rejected → its agents go offline.
+6. UI "Remove" ─► sets revoked_at; that device's token, reconnect code, and
+ all derived agent JWTs are rejected → its agents go offline. The workspace
+ pairing code remains valid.
```
Management endpoints: `GET/POST /api/computers`,
`POST /api/computers/:id/repair` (re-pair an existing computer),
+`POST /api/computers/pairing-code/rotate` (owner-only workspace-code rotation),
`DELETE /api/computers/:id`, and `POST /api/agents/:id/computer`
(assign an agent to a computer + engine). The device token only
authorizes minting JWTs for agents whose `computer_id` matches this
computer; issuing pairing tokens and managing computers require the
owning user's session.
+### Rotate a workspace pairing code
+
+In **Workspace settings → Computer pairing code**, an owner can generate a
+new workspace code without deleting the workspace. This code is for adding
+computers; it is different from the reconnect code shown for one computer.
+Rotation invalidates the old workspace code and leaves already-paired device
+credentials and per-computer reconnect codes active, so connected computers
+continue running. The new code is available from this settings section and the
+Add-Computer command UI.
+
+If a rotation request times out or its response is lost, use **Show current
+code** or **Add a computer** to read the active code. Those actions do not
+rotate it again. A pairing code must not be put in a URL, public issue, log, or
+screenshot.
+
+If the workspace code may have leaked:
+
+1. An owner rotates it in Workspace settings.
+2. Check the computer list for devices you do not recognize.
+3. Remove each suspicious computer. Removal revokes that device and its
+ credentials, including its reconnect code; removing a device alone never
+ rotates the workspace code.
+4. Share details through the private channel in the
+ [security policy](../SECURITY.md), without posting a code or workspace
+ identifier publicly.
+
+| Operation | Workspace pairing code | Paired device credential | Per-computer reconnect code |
+| --- | --- | --- | --- |
+| Rotate workspace code | Old code stops working; new code is active | Remains valid | Remains valid |
+| Remove one computer | Remains valid | That device is revoked | That device's code can no longer pair because it is revoked |
+
+**Security follow-up:** a workspace code can currently re-attach an existing
+computer when the daemon reports the same hostname, replacing that computer's
+device credential. A hostname is not a reliable identity check. A separate,
+compatibility-reviewed change should require an existing computer's own
+reconnect code for that re-attachment. Rotation should therefore be followed
+by a review of the computer list and removal of any device that is not trusted.
+
---
## Observability
diff --git a/server/src/__integration__/computer-pairing-rotation.test.ts b/server/src/__integration__/computer-pairing-rotation.test.ts
new file mode 100644
index 0000000..c7f5e00
--- /dev/null
+++ b/server/src/__integration__/computer-pairing-rotation.test.ts
@@ -0,0 +1,253 @@
+import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
+import { createServer, type Server } from 'node:http'
+import { after, before, beforeEach, test } from 'node:test'
+import { setTimeout as delay } from 'node:timers/promises'
+import { pool } from '../db/pool.js'
+import {
+ issuePairingCode, issueRepairCode, pairComputer, resolveDevice,
+ revokeComputer, rotateCompanyPairingCode,
+} from '../agents/computer/registry.js'
+import {
+ buildApiTestApp, ensureSchemaOnce, resetAllTables, seedUserMembership, teardownAll,
+} from './_helpers.js'
+
+const OWNER_ID = 'pair-rotation-owner'
+const ADMIN_ID = 'pair-rotation-admin'
+const MEMBER_ID = 'pair-rotation-member'
+const OTHER_OWNER_ID = 'pair-rotation-other-owner'
+const servers: Server[] = []
+const bases = new Map<string, string>()
+let anonymousBase = ''
+
+async function listen(app: import('express').Express): Promise<string> {
+ return new Promise((resolve) => {
+ const server = createServer(app).listen(0, () => {
+ const address = server.address()
+ assert.ok(address && typeof address === 'object')
+ servers.push(server)
+ resolve(`http://127.0.0.1:${address.port}`)
+ })
+ })
+}
+
+async function listenFor(userId: string): Promise<string> {
+ return listen(await buildApiTestApp(userId))
+}
+
+function headers(companyId: string): Record<string, string> {
+ return {
+ 'content-type': 'application/json',
+ 'x-company-id': companyId,
+ 'user-agent': 'pairing-rotation-integration-test',
+ }
+}
+
+async function seedWorkspace(): Promise<{ companyId: string; otherCompanyId: string }> {
+ const companyId = `co-${randomUUID().slice(0, 8)}`
+ const otherCompanyId = `co-${randomUUID().slice(0, 8)}`
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
+ [companyId, `Test ${companyId}`, companyId, OWNER_ID],
+ )
+ await seedUserMembership(OWNER_ID, companyId)
+ await seedUserMembership(ADMIN_ID, companyId)
+ await pool.query(`UPDATE company_members SET role = 'admin' WHERE company_id = $1 AND user_id = $2`, [companyId, ADMIN_ID])
+ await seedUserMembership(MEMBER_ID, companyId)
+ await pool.query(`UPDATE company_members SET role = 'member' WHERE company_id = $1 AND user_id = $2`, [companyId, MEMBER_ID])
+
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
+ [otherCompanyId, `Test ${otherCompanyId}`, otherCompanyId, OTHER_OWNER_ID],
+ )
+ await seedUserMembership(OTHER_OWNER_ID, otherCompanyId)
+ return { companyId, otherCompanyId }
+}
+
+async function waitForBlockedQuery(pattern: string): Promise<void> {
+ for (let attempt = 0; attempt < 200; attempt++) {
+ const { rows } = await pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND pid <> pg_backend_pid()
+ AND wait_event_type = 'Lock'
+ AND query ILIKE $1`,
+ [pattern],
+ )
+ if ((rows[0]?.count ?? 0) > 0) return
+ await delay(10)
+ }
+ throw new Error(`query never reached the expected row lock: ${pattern}`)
+}
+
+before(async () => {
+ await ensureSchemaOnce()
+ bases.set(OWNER_ID, await listenFor(OWNER_ID))
+ bases.set(ADMIN_ID, await listenFor(ADMIN_ID))
+ bases.set(MEMBER_ID, await listenFor(MEMBER_ID))
+ bases.set(OTHER_OWNER_ID, await listenFor(OTHER_OWNER_ID))
+ const express = (await import('express')).default
+ const { api } = await import('../api/router.js')
+ const app = express()
+ app.use('/api', api)
+ anonymousBase = await listen(app)
+})
+
+beforeEach(async () => { await resetAllTables() })
+
+after(async () => {
+ await Promise.all(servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))))
+ await teardownAll()
+})
+
+test('[integration] owner rotates the persisted workspace code; old code cannot create or rebind a computer', async () => {
+ const { companyId } = await seedWorkspace()
+ const base = bases.get(OWNER_ID)!
+ const issuedResponse = await fetch(`${base}/api/computers`, { method: 'POST', headers: headers(companyId), body: '{}' })
+ assert.equal(issuedResponse.status, 201)
+ assert.match(issuedResponse.headers.get('cache-control') ?? '', /no-store/)
+ const oldCode = (await issuedResponse.json() as { code: string }).code
+ assert.match(oldCode, /^[A-Za-z0-9_-]{32}$/)
+
+ const trustedPair = await pairComputer({
+ code: oldCode, hostName: 'Trusted host', engines: ['claude'], deferBroadcast: true,
+ })
+ assert.ok(trustedPair)
+ const reconnectCode = await issueRepairCode({
+ companyId, ownerUserId: OWNER_ID, computerId: trustedPair.computerId,
+ })
+ assert.ok(reconnectCode)
+
+ await pool.query(
+ `INSERT INTO computers (id, company_id, name, kind, available_engines, status, credential_hash)
+ VALUES ($1, $2, 'Same host', 'local', '["claude"]'::jsonb, 'offline', 'existing-credential')`,
+ [`existing-${randomUUID().slice(0, 8)}`, companyId],
+ )
+ const existingBefore = await pool.query<{ id: string; credential_hash: string }>(
+ `SELECT id, credential_hash FROM computers WHERE company_id = $1 AND name = 'Same host'`, [companyId],
+ )
+
+ const rotateResponse = await fetch(`${base}/api/computers/pairing-code/rotate`, {
+ method: 'POST', headers: headers(companyId),
+ })
+ assert.equal(rotateResponse.status, 200)
+ assert.match(rotateResponse.headers.get('cache-control') ?? '', /no-store/)
+ const rotated = await rotateResponse.json() as { code: string; expiresInSeconds: null }
+ assert.deepEqual(Object.keys(rotated).sort(), ['code', 'expiresInSeconds'])
+ assert.match(rotated.code, /^[A-Za-z0-9_-]{32}$/)
+ assert.notEqual(rotated.code, oldCode)
+ assert.equal(rotated.expiresInSeconds, null)
+ assert.deepEqual(await resolveDevice(trustedPair.deviceToken), { computerId: trustedPair.computerId, companyId })
+ assert.equal(
+ (await issueRepairCode({ companyId, ownerUserId: OWNER_ID, computerId: trustedPair.computerId }))?.code,
+ reconnectCode.code,
+ )
+
+ const currentResponse = await fetch(`${base}/api/computers`, { method: 'POST', headers: headers(companyId), body: '{}' })
+ assert.equal(currentResponse.status, 201)
+ const current = await currentResponse.json() as { code: string }
+ assert.equal(current.code, rotated.code)
+
+ assert.equal(await pairComputer({ code: oldCode, hostName: 'New host', engines: ['claude'], deferBroadcast: true }), null)
+ assert.equal(await pairComputer({ code: oldCode, hostName: 'Same host', engines: ['claude'], deferBroadcast: true }), null)
+ const existingAfter = await pool.query<{ id: string; credential_hash: string }>(
+ `SELECT id, credential_hash FROM computers WHERE company_id = $1 AND name = 'Same host'`, [companyId],
+ )
+ assert.deepEqual(existingAfter.rows, existingBefore.rows)
+ const paired = await pairComputer({ code: rotated.code, hostName: 'Same host', engines: ['claude'], deferBroadcast: true })
+ assert.equal(paired?.computerId, existingBefore.rows[0].id)
+ assert.ok(paired?.deviceToken)
+ const sameHostReconnectCode = await issueRepairCode({
+ companyId, ownerUserId: OWNER_ID, computerId: paired!.computerId,
+ })
+ assert.ok(sameHostReconnectCode)
+ assert.equal(await revokeComputer({ computerId: paired!.computerId, companyId }), true)
+ assert.equal(await resolveDevice(paired!.deviceToken), null)
+ assert.equal(await pairComputer({
+ code: sameHostReconnectCode.code, hostName: 'Same host', deferBroadcast: true,
+ }), null)
+
+ const { rows: events } = await pool.query<{
+ user_id: string; company_id: string; ip: string | null; user_agent: string | null; kind: string; detail: unknown
+ }>(
+ `SELECT user_id, company_id, ip, user_agent, kind, detail
+ FROM audit_events WHERE kind = 'company_pair_token_rotated'`,
+ )
+ assert.equal(events.length, 1)
+ assert.equal(events[0].user_id, OWNER_ID)
+ assert.equal(events[0].company_id, companyId)
+ assert.ok(events[0].ip)
+ assert.equal(events[0].user_agent, 'pairing-rotation-integration-test')
+ const auditText = JSON.stringify(events[0])
+ assert.ok(!auditText.includes(oldCode))
+ assert.ok(!auditText.includes(rotated.code))
+})
+
+test('[integration] only an owner in the active workspace may rotate the code', async () => {
+ const { companyId } = await seedWorkspace()
+ const admin = await fetch(`${bases.get(ADMIN_ID)!}/api/computers/pairing-code/rotate`, {
+ method: 'POST', headers: headers(companyId),
+ })
+ const member = await fetch(`${bases.get(MEMBER_ID)!}/api/computers/pairing-code/rotate`, {
+ method: 'POST', headers: headers(companyId),
+ })
+ const otherWorkspace = await fetch(`${bases.get(OTHER_OWNER_ID)!}/api/computers/pairing-code/rotate`, {
+ method: 'POST', headers: headers(companyId),
+ })
+ const anonymous = await fetch(`${anonymousBase}/api/computers/pairing-code/rotate`, {
+ method: 'POST', headers: headers(companyId),
+ })
+ assert.equal(admin.status, 403)
+ assert.equal(member.status, 403)
+ assert.equal(otherWorkspace.status, 403)
+ assert.equal(anonymous.status, 401)
+
+ const { rows } = await pool.query<{ pair_token: string | null }>(
+ `SELECT pair_token FROM companies WHERE id = $1`, [companyId],
+ )
+ assert.equal(rows[0].pair_token, null)
+ const audit = await pool.query(`SELECT 1 FROM audit_events WHERE kind = 'company_pair_token_rotated'`)
+ assert.equal(audit.rowCount, 0)
+})
+
+test('[integration] pair lookup waits behind rotation and rechecks the old code after rotation commits', async () => {
+ const { companyId } = await seedWorkspace()
+ const oldCode = await issuePairingCode({ companyId, ownerUserId: OWNER_ID })
+ const blocker = await pool.connect()
+ let committed = false
+ let rotation: ReturnType<typeof rotateCompanyPairingCode> | undefined
+ let pairing: ReturnType<typeof pairComputer> | undefined
+ let testError: unknown = null
+ try {
+ await blocker.query('BEGIN')
+ await blocker.query(`SELECT id FROM companies WHERE id = $1 FOR UPDATE`, [companyId])
+
+ rotation = rotateCompanyPairingCode({ companyId, ownerUserId: OWNER_ID })
+ void rotation.catch(() => {})
+ await waitForBlockedQuery('%UPDATE companies SET pair_token = $1 WHERE id = $2 RETURNING id%')
+
+ pairing = pairComputer({ code: oldCode.code, hostName: 'Racing host', engines: ['claude'], deferBroadcast: true })
+ void pairing.catch(() => {})
+ await waitForBlockedQuery('%SELECT id, owner_user_id%FROM companies%pair_token = $1%FOR SHARE%')
+
+ await blocker.query('COMMIT')
+ committed = true
+ } catch (error) {
+ testError = error
+ } finally {
+ if (!committed) await blocker.query('ROLLBACK').catch(() => {})
+ blocker.release()
+ }
+
+ if (testError) {
+ await Promise.allSettled([rotation, pairing].filter((task): task is NonNullable<typeof task> => Boolean(task)))
+ throw testError
+ }
+ assert.ok(rotation && pairing)
+ const [rotated, paired] = await Promise.all([rotation, pairing])
+ assert.ok('code' in rotated)
+ assert.notEqual(rotated.code, oldCode.code)
+ assert.equal(paired, null)
+ assert.equal(await pairComputer({ code: oldCode.code, hostName: 'After rotation', deferBroadcast: true }), null)
+})
diff --git a/server/src/__tests__/agent-computer-pairing-token.test.ts b/server/src/__tests__/agent-computer-pairing-token.test.ts
index 19134ea..aae8db8 100644
--- a/server/src/__tests__/agent-computer-pairing-token.test.ts
+++ b/server/src/__tests__/agent-computer-pairing-token.test.ts
@@ -13,23 +13,28 @@ const registry = await import('../agents/computer/registry.js')
const { pool } = await import('../db/pool.js')
const originalQuery = pool.query.bind(pool)
+const originalConnect = pool.connect.bind(pool)
type QueryCall = { sql: string; params: unknown[] }
function installPoolMock(handler: (call: QueryCall) => { rows?: unknown[]; rowCount?: number }) {
const calls: QueryCall[] = []
+ const query = async (sql: string, params: unknown[] = []) => {
+ const call = { sql, params }
+ calls.push(call)
+ if (/^(BEGIN|COMMIT|ROLLBACK)$/.test(sql.trim())) return { rows: [], rowCount: 0 }
+ const out = handler(call)
+ return { rows: out.rows ?? [], rowCount: out.rowCount ?? (out.rows?.length ?? 0) }
+ }
;(pool as unknown as { query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number }> }).query =
- async (sql: string, params: unknown[] = []) => {
- const call = { sql, params }
- calls.push(call)
- const out = handler(call)
- return { rows: out.rows ?? [], rowCount: out.rowCount ?? (out.rows?.length ?? 0) }
- }
+ query
+ ;(pool as unknown as { connect: () => Promise<unknown> }).connect = async () => ({ query, release() {} })
return calls
}
afterEach(() => {
;(pool as unknown as { query: typeof originalQuery }).query = originalQuery
+ ;(pool as unknown as { connect: typeof originalConnect }).connect = originalConnect
})
after(async () => {
@@ -53,8 +58,8 @@ test('company add token is persistent and reattaches an existing host by name',
}
if (/UPDATE companies SET pair_token/.test(sql)) return { rowCount: 1 }
if (/SELECT id, company_id/.test(sql)) return { rows: [] }
- if (/SELECT id AS company_id, owner_user_id FROM companies/.test(sql)) {
- return { rows: [{ company_id: 'co-1', owner_user_id: 'u-1' }] }
+ if (/SELECT id, owner_user_id FROM companies/.test(sql)) {
+ return { rows: [{ id: 'co-1', owner_user_id: 'u-1' }] }
}
if (/SELECT id FROM computers/.test(sql)) return { rows: [{ id: 'comp-existing' }] }
if (/UPDATE computers\s+SET credential_hash/.test(sql)) return { rowCount: 1 }
@@ -154,8 +159,8 @@ test('pairComputer accepts antigravity engine as primary and stores it in availa
const calls = installPoolMock(({ sql }) => {
if (/SELECT pair_token FROM companies/.test(sql)) return { rows: [{ pair_token: 'company-token' }] }
if (/SELECT id, company_id/.test(sql)) return { rows: [] }
- if (/SELECT id AS company_id, owner_user_id FROM companies/.test(sql)) {
- return { rows: [{ company_id: 'co-1', owner_user_id: 'u-1' }] }
+ if (/SELECT id, owner_user_id FROM companies/.test(sql)) {
+ return { rows: [{ id: 'co-1', owner_user_id: 'u-1' }] }
}
if (/SELECT id FROM computers/.test(sql)) return { rows: [{ id: 'comp-antigravity' }] }
if (/UPDATE computers\s+SET credential_hash/.test(sql)) return { rowCount: 1 }
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index 9f3b34c..125287a 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -17,6 +17,7 @@
import { type ProviderProfileMetadata, isProviderProfileId, sanitizeProviderProfiles } from './provider-profiles.js'
import { createHash, randomBytes, randomUUID } from 'node:crypto'
import { pool } from '../../db/pool.js'
+import { audit } from '../../auth.js'
import { CH_STATUS, publish } from '../../redis.js'
import { normalizeTier, type Tier } from '../../tier.js'
import { signAgentToken } from '../runtime/jwt.js'
@@ -380,6 +381,41 @@ export async function issuePairingCode(args: {
return { code: token, expiresInSeconds: null }
}
+/** Rotate the workspace's add-computer token. Owner authorization is enforced
+ * by the route before this data-access operation. Existing computer
+ * credentials and computer-specific reconnect tokens remain valid. */
+export async function rotateCompanyPairingCode(args: {
+ companyId: string
+ ownerUserId: string
+ ip?: string | null
+ userAgent?: string | null
+}): Promise<{ code: string; expiresInSeconds: null } | { error: 'not_found' }> {
+ const code = randomBytes(24).toString('base64url')
+ let updated: { rows: { id: string }[] }
+ try {
+ updated = await pool.query<{ id: string }>(
+ `UPDATE companies SET pair_token = $1 WHERE id = $2 RETURNING id`,
+ [code, args.companyId],
+ )
+ } catch {
+ // PostgreSQL unique-violation details can include the conflicting value.
+ // Never propagate or log an exception that might contain the fresh code.
+ throw new Error('workspace pairing code rotation failed')
+ }
+ if (!updated.rows[0]) return { error: 'not_found' }
+
+ // Audit is deliberately best-effort: the UPDATE has already invalidated
+ // the previous code, and audit availability must not restore it.
+ await audit({
+ kind: 'company_pair_token_rotated',
+ userId: args.ownerUserId,
+ companyId: args.companyId,
+ ip: args.ip,
+ userAgent: args.userAgent,
+ })
+ return { code, expiresInSeconds: null }
+}
+
/** Return a persistent reconnect token for one existing non-cloud computer.
* Unlike the company add token, this token is bound to the computer row itself,
* so running the command from the Computer detail view re-attaches that exact
@@ -472,48 +508,67 @@ export async function pairComputer(args: {
return { computerId: id, companyId, deviceToken }
}
- const { rows } = await pool.query<{ company_id: string; owner_user_id: string | null }>(
- `SELECT id AS company_id, owner_user_id FROM companies WHERE pair_token = $1 LIMIT 1`,
- [args.code],
- )
- if (!rows[0]) return null
- const companyId = rows[0].company_id
- const ownerUserId = rows[0].owner_user_id
+ // A workspace token is read and redeemed under one row lock. Rotation's
+ // UPDATE waits for this transaction, so after a rotation returns no pairing
+ // that started with the old code can still commit. Reconnect tokens above
+ // remain computer-scoped and keep their existing path and semantics.
+ const client = await pool.connect()
+ let paired: { computerId: string; companyId: string; deviceToken: string } | null = null
+ try {
+ await client.query('BEGIN')
+ const { rows } = await client.query<{ id: string; owner_user_id: string | null }>(
+ `SELECT id, owner_user_id FROM companies WHERE pair_token = $1 FOR SHARE`,
+ [args.code],
+ )
+ if (!rows[0]) {
+ await client.query('ROLLBACK')
+ return null
+ }
+ const companyId = rows[0].id
+ const ownerUserId = rows[0].owner_user_id
- // Re-attach if a non-cloud computer with this hostname already exists in the
- // company — a re-run of the (now persistent) command from the same machine.
- // Re-mint the device token + refresh engines/status; never create a duplicate.
- const existing = await pool.query<{ id: string }>(
- `SELECT id FROM computers
- WHERE company_id = $1 AND kind <> 'cloud' AND revoked_at IS NULL AND name = $2
- ORDER BY paired_at DESC NULLS LAST LIMIT 1`,
- [companyId, name],
- )
- if (existing.rows[0]) {
- const id = existing.rows[0].id
- await pool.query(
- `UPDATE computers
- SET credential_hash = $1, available_engines = $2::jsonb,
- daemon_version = COALESCE($4, daemon_version),
- daemon_supervised = COALESCE($5, daemon_supervised),
- detected_engines = $6::jsonb, engines_detected_at = NOW(), detect_requested_at = NULL,
- status = 'online', last_seen_at = NOW(), paired_at = NOW(), revoked_at = NULL
- WHERE id = $3`,
- [hashToken(deviceToken), JSON.stringify(engines), id, version, supervised, detectedJson],
+ // Re-attach if a non-cloud computer with this hostname already exists in
+ // the company — a re-run of the persistent command from the same machine.
+ // Re-mint the device token + refresh engines/status; never create a duplicate.
+ const existing = await client.query<{ id: string }>(
+ `SELECT id FROM computers
+ WHERE company_id = $1 AND kind <> 'cloud' AND revoked_at IS NULL AND name = $2
+ ORDER BY paired_at DESC NULLS LAST LIMIT 1`,
+ [companyId, name],
)
- if (!args.deferBroadcast) await broadcastComputerStatus(id, companyId, 'online')
- return { computerId: id, companyId, deviceToken }
+ if (existing.rows[0]) {
+ const id = existing.rows[0].id
+ await client.query(
+ `UPDATE computers
+ SET credential_hash = $1, available_engines = $2::jsonb,
+ daemon_version = COALESCE($4, daemon_version),
+ daemon_supervised = COALESCE($5, daemon_supervised),
+ detected_engines = $6::jsonb, engines_detected_at = NOW(), detect_requested_at = NULL,
+ status = 'online', last_seen_at = NOW(), paired_at = NOW(), revoked_at = NULL
+ WHERE id = $3`,
+ [hashToken(deviceToken), JSON.stringify(engines), id, version, supervised, detectedJson],
+ )
+ paired = { computerId: id, companyId, deviceToken }
+ } else {
+ const computerId = `comp-${randomUUID().slice(0, 12)}`
+ await client.query(
+ `INSERT INTO computers
+ (id, company_id, owner_user_id, name, kind, available_engines, status, credential_hash, paired_at, last_seen_at, daemon_version, daemon_supervised, detected_engines, engines_detected_at)
+ VALUES ($1, $2, $3, $4, 'local', $5::jsonb, 'online', $6, NOW(), NOW(), $7, $8, $9::jsonb, NOW())`,
+ [computerId, companyId, ownerUserId, name, JSON.stringify(engines), hashToken(deviceToken), version, supervised, detectedJson],
+ )
+ paired = { computerId, companyId, deviceToken }
+ }
+ await client.query('COMMIT')
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw error
+ } finally {
+ client.release()
}
-
- const computerId = `comp-${randomUUID().slice(0, 12)}`
- await pool.query(
- `INSERT INTO computers
- (id, company_id, owner_user_id, name, kind, available_engines, status, credential_hash, paired_at, last_seen_at, daemon_version, daemon_supervised, detected_engines, engines_detected_at)
- VALUES ($1, $2, $3, $4, 'local', $5::jsonb, 'online', $6, NOW(), NOW(), $7, $8, $9::jsonb, NOW())`,
- [computerId, companyId, ownerUserId, name, JSON.stringify(engines), hashToken(deviceToken), version, supervised, detectedJson],
- )
- if (!args.deferBroadcast) await broadcastComputerStatus(computerId, companyId, 'online')
- return { computerId, companyId, deviceToken }
+ if (!paired) return null
+ if (!args.deferBroadcast) await broadcastComputerStatus(paired.computerId, paired.companyId, 'online')
+ return paired
}
/** Daemon liveness ping. Bumps last_seen_at + the reported version; flips
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index e8cc07b..a54205b 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -42,7 +42,7 @@ import {
listComputers, revokeComputer, assignAgentToComputer, heartbeatComputer,
cloudComputerId, issueRepairCode, requestEngineDetect, reportDetectedEngines,
setComputerDefaultEngine, updateEngineDefaults, getEngineDefaults,
- PAIRABLE_ENGINES, type EngineId,
+ rotateCompanyPairingCode, PAIRABLE_ENGINES, type EngineId,
} from '../agents/computer/registry.js'
import { attachComputerControlStream, deliverEngineDetect } from '../agents/computer/control-bus.js'
import { companyTier } from '../tier.js'
@@ -1183,13 +1183,34 @@ api.get('/computers', safe(async (req, res) => {
// No computer row is created here — pairComputer creates it once the daemon
// pairs and reports the machine's real hostname.
api.post('/computers', safe(async (req, res) => {
+ res.setHeader('Cache-Control', 'no-store')
const { userId: uid, companyId } = await requireCompanyRole(req)
res.status(201).json(await issuePairingCode({ companyId, ownerUserId: uid }))
}))
+// Replace the active workspace add-computer token (owner only). Existing
+// paired device credentials and their computer-specific reconnect tokens stay
+// valid. Removing a computer only revokes that device; it does not rotate this
+// workspace token.
+api.post('/computers/pairing-code/rotate', safe(async (req, res) => {
+ res.setHeader('Cache-Control', 'no-store')
+ const { userId, companyId } = await requireCompanyRole(req, OWNER_ONLY)
+ const result = await rotateCompanyPairingCode({
+ companyId,
+ ownerUserId: userId,
+ ip: req.ip,
+ userAgent: req.get('user-agent'),
+ })
+ if ('error' in result) {
+ throw new HttpError(404, 'workspace not found')
+ }
+ res.json(result)
+}))
+
// Issue a persistent re-pair token for an existing computer — reconnect it (and its
// agents) by running the daemon again with this code (owner/admin).
api.post('/computers/:id/repair', safe(async (req, res) => {
+ res.setHeader('Cache-Control', 'no-store')
const { userId: uid, companyId } = await requireCompanyRole(req)
const out = await issueRepairCode({ companyId, ownerUserId: uid, computerId: String(req.params.id) })
if (!out) throw new HttpError(404, 'computer not found or not re-pairable')
diff --git a/src/api/client.ts b/src/api/client.ts
index b23fd6e..6c288a1 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -984,6 +984,12 @@ export const api = {
requestPairingCode: () =>
http<{ code: string; expiresInSeconds: number | null }>(
'/computers', { method: 'POST', body: '{}' }),
+ /** Rotate the active workspace add-computer code. This POST is deliberately
+ * never retried: if its response is lost, requestPairingCode() reads back
+ * the server's current code without rotating it again. */
+ rotatePairingCode: () =>
+ http<{ code: string; expiresInSeconds: null }>(
+ '/computers/pairing-code/rotate', { method: 'POST' }),
/** Revoke a paired computer (its device token + agent JWTs stop working). */
deleteComputer: (id: string) =>
http<{ ok: boolean }>(`/computers/${encodeURIComponent(id)}`, { method: 'DELETE' }),
diff --git a/src/components/WorkspaceSettingsModal.tsx b/src/components/WorkspaceSettingsModal.tsx
index 01157b0..9b9de15 100644
--- a/src/components/WorkspaceSettingsModal.tsx
+++ b/src/components/WorkspaceSettingsModal.tsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { type ApiWorkspaceMember, api, ws } from '@/api/client'
import { useT } from '@/lib/i18n'
import { type AuthCompany, useAuth } from '@/stores/auth'
+import { usePairingCodes } from '@/stores/pairing-codes'
interface Props {
company: AuthCompany
@@ -14,6 +15,7 @@ export function WorkspaceSettingsModal({ company, companyCount, onInvite, onClos
const t = useT()
const meId = useAuth((s) => s.user?.id)
const removeCompany = useAuth((s) => s.removeCompany)
+ const pairingCode = usePairingCodes((s) => s.companyId === company.id ? s.code : null)
const [members, setMembers] = useState<ApiWorkspaceMember[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@@ -21,6 +23,8 @@ export function WorkspaceSettingsModal({ company, companyCount, onInvite, onClos
const [deleteConfirmation, setDeleteConfirmation] = useState('')
const [deleting, setDeleting] = useState(false)
const [deleteError, setDeleteError] = useState<string | null>(null)
+ const [pairingBusy, setPairingBusy] = useState(false)
+ const [pairingError, setPairingError] = useState<string | null>(null)
const memberLoadGeneration = useRef(0)
useEffect(() => {
@@ -57,6 +61,44 @@ export function WorkspaceSettingsModal({ company, companyCount, onInvite, onClos
void loadMembers(false)
}), [company.id, loadMembers])
+ const showCurrentPairingCode = async () => {
+ if (useAuth.getState().activeCompanyId !== company.id) {
+ setPairingError(t('workspace.pairingCodeWrongWorkspace'))
+ return
+ }
+ setPairingError(null); setPairingBusy(true)
+ try {
+ const version = usePairingCodes.getState().beginRequest(company.id)
+ const result = await api.requestPairingCode()
+ usePairingCodes.getState().setCodeIfCurrent(company.id, version, result.code)
+ } catch (reason) {
+ setPairingError(reason instanceof Error ? reason.message : String(reason))
+ } finally {
+ setPairingBusy(false)
+ }
+ }
+
+ const rotatePairingCode = async () => {
+ if (!window.confirm(t('workspace.rotatePairingCodeConfirm'))) return
+ if (useAuth.getState().activeCompanyId !== company.id) {
+ setPairingError(t('workspace.pairingCodeWrongWorkspace'))
+ return
+ }
+ setPairingError(null); setPairingBusy(true)
+ // The server may commit even if the response is lost. Clear the old code
+ // immediately; the explicit "Show current code" action safely reads back
+ // the active one without performing another rotation.
+ const version = usePairingCodes.getState().beginRequest(company.id, true)
+ try {
+ const result = await api.rotatePairingCode()
+ usePairingCodes.getState().setCodeIfCurrent(company.id, version, result.code)
+ } catch (reason) {
+ setPairingError(reason instanceof Error ? reason.message : String(reason))
+ } finally {
+ setPairingBusy(false)
+ }
+ }
+
const changeRole = async (member: ApiWorkspaceMember, role: 'member' | 'admin') => {
if (member.role === role) return
setBusyMemberId(member.id); setError(null)
@@ -185,6 +227,35 @@ export function WorkspaceSettingsModal({ company, companyCount, onInvite, onClos
)}
</section>
+ {company.role === 'owner' && (
+ <section className="mx-5 mb-4 rounded-[12px] border border-ink-100 bg-cloud p-4">
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <h3 className="text-[13px] font-semibold text-ink-800">{t('workspace.pairingCodeTitle')}</h3>
+ <p className="mt-1 text-[11.5px] leading-relaxed text-ink-500">{t('workspace.pairingCodeHelp')}</p>
+ </div>
+ </div>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <button type="button" onClick={() => void showCurrentPairingCode()} disabled={pairingBusy}
+ className="rounded-[8px] border border-ink-200 bg-paper px-3 py-1.5 text-[11.5px] font-semibold text-ink-700 hover:bg-cloud disabled:opacity-50">
+ {pairingBusy ? t('workspace.pairingCodeLoading') : t('workspace.showPairingCode')}
+ </button>
+ <button type="button" onClick={() => void rotatePairingCode()} disabled={pairingBusy}
+ className="rounded-[8px] border border-coral/35 bg-paper px-3 py-1.5 text-[11.5px] font-semibold text-coral-deep hover:bg-coral-soft/25 disabled:opacity-50">
+ {pairingBusy ? t('workspace.rotatingPairingCode') : t('workspace.rotatePairingCode')}
+ </button>
+ </div>
+ {pairingError && <div className="mt-2 text-[11.5px] text-coral-deep">{pairingError}</div>}
+ {pairingCode && (
+ <div className="mt-3 rounded-[9px] bg-paper border border-ink-100 p-3">
+ <div className="text-[10.5px] font-semibold text-ink-500">{t('workspace.currentPairingCode')}</div>
+ <code className="mt-1 block break-all select-all text-[12px] text-ink-800">{pairingCode}</code>
+ <p className="mt-2 text-[11px] leading-relaxed text-ink-500">{t('workspace.pairingCodeUseFlow')}</p>
+ </div>
+ )}
+ </section>
+ )}
+
{company.role === 'owner' && (
<section className="m-5 mt-1 rounded-[12px] border border-coral/35 bg-coral-soft/15 p-4">
<h3 className="text-[13px] font-semibold text-coral-deep">{t('workspace.dangerTitle')}</h3>
diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsx
index 694e68a..a071357 100644
--- a/src/desktop/MeView.tsx
+++ b/src/desktop/MeView.tsx
@@ -5,6 +5,7 @@ import { usePrefs } from '@/stores/preferences'
import { useSoundStore } from '@/stores/sound'
import { useDevtools } from '@/stores/devtools'
import { useAuth } from '@/stores/auth'
+import { usePairingCodes } from '@/stores/pairing-codes'
import { Avatar } from '@/components/Avatar'
import { Checkbox } from '@/components/Checkbox'
import { AppearancePicker, ChatLayoutPicker } from '@/components/AppearancePicker'
@@ -826,12 +827,13 @@ function asRunnableEngine(id: string): EngineId | null {
function ComputersTab() {
const t = useT()
+ const companyId = useAuth((s) => s.activeCompanyId)
+ const code = usePairingCodes((s) => s.companyId === companyId ? s.code : null)
const byId = useComputers((s) => s.byId)
const loaded = useComputers((s) => s.loaded)
const participants = useParticipants((s) => s.byId)
const [busy, setBusy] = useState(false)
const [err, setErr] = useState<string | null>(null)
- const [code, setCode] = useState<string | null>(null)
const [copied, setCopied] = useState(false)
// Engine for a NEWLY added computer's starter/assigned agents. Claude is the
// default (no flag → daemon auto-detects); every other pick is named
@@ -898,6 +900,7 @@ function ComputersTab() {
}, [])
useEffect(() => { if (!repairCopied) return; const id = window.setTimeout(() => setRepairCopied(false), 1600); return () => window.clearTimeout(id) }, [repairCopied])
useEffect(() => { if (!copiedCli) return; const id = window.setTimeout(() => setCopiedCli(null), 1600); return () => window.clearTimeout(id) }, [copiedCli])
+ useEffect(() => { setCopied(false) }, [code, companyId])
async function toggleRepair(id: string) {
if (repairFor === id) { setRepairFor(null); setRepairCode(null); return }
@@ -935,10 +938,13 @@ function ComputersTab() {
// reports the machine's real hostname — so no placeholder row, and it shows
// up here (named after the machine) once paired, via the WS status event.
async function addComputer() {
+ const targetCompanyId = useAuth.getState().activeCompanyId
+ if (!targetCompanyId) return
setErr(null); setBusy(true)
try {
+ const version = usePairingCodes.getState().beginRequest(targetCompanyId)
const res = await api.requestPairingCode()
- setCode(res.code)
+ usePairingCodes.getState().setCodeIfCurrent(targetCompanyId, version, res.code)
} catch (e) {
setErr(e instanceof Error ? e.message : String(e))
} finally { setBusy(false) }
@@ -1361,7 +1367,7 @@ function ComputersTab() {
</>
) : t('me.copyCommand')}
</button>
- <button type="button" onClick={() => setCode(null)}
+ <button type="button" onClick={() => usePairingCodes.getState().clear()}
className="text-[12px] font-semibold px-3 py-1.5 rounded-[9px] border border-ink-100 text-ink-600">{t('me.done')}</button>
</div>
<style>{`
diff --git a/src/desktop/Onboarding.tsx b/src/desktop/Onboarding.tsx
index 0c970cc..326468f 100644
--- a/src/desktop/Onboarding.tsx
+++ b/src/desktop/Onboarding.tsx
@@ -4,6 +4,8 @@ import { useComputers } from '@/stores/computers'
import { TitleBar } from '@/desktop/TitleBar'
import { useT } from '@/lib/i18n'
import { RUNNABLE_ENGINES, engineLabel, type RunnableEngineId } from '@/lib/engines'
+import { useAuth } from '@/stores/auth'
+import { usePairingCodes } from '@/stores/pairing-codes'
/**
* First-run gate for free-tier users: their agents run on their own machine
@@ -14,8 +16,10 @@ import { RUNNABLE_ENGINES, engineLabel, type RunnableEngineId } from '@/lib/engi
*/
export function Onboarding() {
const t = useT()
+ const companyId = useAuth((s) => s.activeCompanyId)
+ const companyRole = useAuth((s) => s.companies.find((company) => company.id === s.activeCompanyId)?.role)
+ const code = usePairingCodes((s) => s.companyId === companyId ? s.code : null)
const [busy, setBusy] = useState(false)
- const [code, setCode] = useState<string | null>(null)
const [err, setErr] = useState<string | null>(null)
const [copied, setCopied] = useState(false)
// The engine the starter team (and agents later assigned here) will run on.
@@ -34,6 +38,7 @@ export function Onboarding() {
const t = window.setTimeout(() => setCopied(false), 1600)
return () => window.clearTimeout(t)
}, [copied])
+ useEffect(() => { setCopied(false) }, [code, companyId])
const origin = getPairingServerOrigin()
// Every non-default engine, not just Codex: without the flag the daemon
@@ -44,12 +49,33 @@ export function Onboarding() {
const cmd = code ? `npx cumora@latest agent computer --pair ${code}${origin ? ` --server ${origin}` : ''}${engineFlag}${serviceFlag}` : ''
async function getCode() {
+ const targetCompanyId = useAuth.getState().activeCompanyId
+ if (!targetCompanyId) return
setErr(null); setBusy(true)
- try { setCode((await api.requestPairingCode()).code) }
+ try {
+ const version = usePairingCodes.getState().beginRequest(targetCompanyId)
+ const result = await api.requestPairingCode()
+ usePairingCodes.getState().setCodeIfCurrent(targetCompanyId, version, result.code)
+ }
catch (e) { setErr(e instanceof Error ? e.message : String(e)) }
finally { setBusy(false) }
}
+ async function rotateCode() {
+ const targetCompanyId = useAuth.getState().activeCompanyId
+ if (!targetCompanyId || !window.confirm(t('onboard.rotateConfirm'))) return
+ setErr(null); setBusy(true); setCopied(false)
+ // A lost response may follow a successful commit, so never leave an old
+ // command visible while the outcome is unknown. "Add a computer" rereads
+ // the active code without rotating it again.
+ const version = usePairingCodes.getState().beginRequest(targetCompanyId, true)
+ try {
+ const result = await api.rotatePairingCode()
+ usePairingCodes.getState().setCodeIfCurrent(targetCompanyId, version, result.code)
+ } catch (e) { setErr(e instanceof Error ? e.message : String(e)) }
+ finally { setBusy(false) }
+ }
+
return (
// TitleBar carries the window drag region (and traffic-light spacing) — the
// onboarding screen replaces the whole app, so without it the window can't
@@ -126,6 +152,17 @@ export function Onboarding() {
)}
</div>
+ {companyRole === 'owner' && (
+ <section className="mt-4 rounded-[12px] border border-ink-100 bg-paper p-4">
+ <h2 className="text-[12.5px] font-semibold text-ink-800">{t('onboard.securityTitle')}</h2>
+ <p className="mt-1 text-[11.5px] leading-relaxed text-ink-500">{t('onboard.securityHelp')}</p>
+ <button type="button" onClick={() => void rotateCode()} disabled={busy}
+ className="mt-3 rounded-[8px] border border-ink-200 px-3 py-1.5 text-[11.5px] font-semibold text-ink-700 hover:bg-cloud disabled:opacity-50">
+ {busy ? t('onboard.rotating') : t('onboard.rotate')}
+ </button>
+ </section>
+ )}
+
<p className="text-[12px] text-ink-400 mt-4">
{t('onboard.cloudCta')} <span className="text-skype-deep">{t('onboard.upgradePro')}</span> {t('onboard.cloudRun')}
</p>
diff --git a/src/locales/en.ts b/src/locales/en.ts
index a7e6a3f..829d0bf 100644
--- a/src/locales/en.ts
+++ b/src/locales/en.ts
@@ -1115,7 +1115,12 @@ export const en = {
'onboard.generating': 'Generating…',
'onboard.addComputer': 'Add a computer',
'onboard.runThis': 'Run this on that machine:',
- 'onboard.tokenHint': 'This pairing token stays valid. The computer appears here and you’ll continue automatically once it connects.',
+ 'onboard.tokenHint': 'This workspace code adds computers and stays valid until rotated. Each paired computer has a separate reconnect code; rotating the workspace code does not disconnect it.',
+ 'onboard.securityTitle': 'Workspace pairing code security',
+ 'onboard.securityHelp': 'If this code may have leaked, rotate it and inspect the computer list. Remove any suspicious computer. Removing a computer revokes only that device; it does not rotate this workspace code. If rotation times out, use “Add a computer” to read the active code without rotating again.',
+ 'onboard.rotate': 'Pairing code leaked? Generate a new one',
+ 'onboard.rotating': 'Generating…',
+ 'onboard.rotateConfirm': 'Generate a new workspace pairing code? Commands using the old code will stop working, while already paired computers stay online. Afterward, inspect the computer list for devices you do not recognize.',
'onboard.engine': 'Engine',
'onboard.engineHint': 'just the default — this computer can still run agents on any detected engine',
'onboard.background': 'Keep it running in the background',
@@ -1287,14 +1292,14 @@ export const en = {
'me.hideAction': 'Hide',
'me.reconnect': 'Reconnect',
'me.remove': 'Remove',
- 'me.removeConfirm': 'Remove "{label}"? Its agents will go offline until you re-pair.',
- 'me.repairHint': 'Run this on “{name}” to reconnect it — its agents stay attached. This token stays valid.',
+ 'me.removeConfirm': 'Remove "{label}"? Its agents will go offline until you re-pair. This revokes only this device; it does not rotate the workspace pairing code.',
+ 'me.repairHint': 'Run this computer-specific reconnect command on “{name}” to reconnect it — its agents stay attached. This code is separate from the workspace code for adding computers.',
'me.copyCommand': 'Copy command',
'me.copied': '✓ Copied!',
'me.copy': 'Copy',
'me.copiedShort': '✓ Copied',
'me.runOnHost': 'Run this on the machine you want to host agents:',
- 'me.engineRequired': 'Needs <span class="font-mono not-italic">claude</span>, <span class="font-mono not-italic">codex</span>, <span class="font-mono not-italic">grok</span>, <span class="font-mono not-italic">cursor-agent</span>, or <span class="font-mono not-italic">opencode</span> installed. The computer names itself after that machine and appears here once paired. This token stays valid.',
+ 'me.engineRequired': 'Needs <span class="font-mono not-italic">claude</span>, <span class="font-mono not-italic">codex</span>, <span class="font-mono not-italic">grok</span>, <span class="font-mono not-italic">cursor-agent</span>, or <span class="font-mono not-italic">opencode</span> installed. This is the workspace code for adding computers; it stays valid until rotated. Use a computer-specific reconnect code to reconnect one existing computer.',
'me.keepInBackground': 'Keep it running in the background',
'me.keepInBackgroundDetail': '— auto-start when you sign in, auto-restart on crash, auto-update. Otherwise this terminal has to stay open.',
'me.done': 'Done',
@@ -1513,6 +1518,16 @@ export const en = {
'workspace.roleMember': 'Member',
'workspace.removeBtn': 'Remove',
'workspace.removeConfirm': 'Remove {name} from this workspace? They will immediately lose access, but their message history will remain.',
+ 'workspace.pairingCodeTitle': 'Computer pairing code',
+ 'workspace.pairingCodeHelp': 'The workspace code adds computers; each computer has a separate reconnect code. Rotation invalidates only the old workspace code, while paired computers and reconnect codes stay valid. Removing a computer revokes only that device and does not rotate the workspace code. After rotating, inspect the computer list and remove suspicious devices individually.',
+ 'workspace.rotatePairingCodeConfirm': 'Generate a new workspace pairing code? Commands using the old code will stop working, while already paired computers stay online. You should inspect the computer list afterward.',
+ 'workspace.rotatePairingCode': 'Generate new code',
+ 'workspace.rotatingPairingCode': 'Rotating…',
+ 'workspace.showPairingCode': 'Show current code',
+ 'workspace.pairingCodeLoading': 'Loading…',
+ 'workspace.currentPairingCode': 'Current workspace code',
+ 'workspace.pairingCodeUseFlow': 'To use it, open Me → Computers and copy the add-computer command there.',
+ 'workspace.pairingCodeWrongWorkspace': 'Switch back to this workspace before viewing or changing its pairing code.',
'workspace.dangerTitle': 'Delete workspace',
'workspace.deleteHelp': 'Permanently deletes this workspace, including conversations, agents, documents, boards, calendar data, and attachments. This cannot be undone.',
'workspace.onlyWorkspace': 'You cannot delete your only workspace. Create or join another workspace first.',
diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.ts
index 4ca8ee1..3fb3108 100644
--- a/src/locales/zh-CN.ts
+++ b/src/locales/zh-CN.ts
@@ -1116,7 +1116,12 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'onboard.generating': '生成中…',
'onboard.addComputer': '添加一台计算机',
'onboard.runThis': '在那台机器上跑这条命令:',
- 'onboard.tokenHint': '配对码长期有效。计算机连上后会在这里出现,连接成功会自动继续。',
+ 'onboard.tokenHint': '这是用于添加计算机的工作区配对码,除非轮换,否则一直有效。每台已配对计算机都有独立的重连码;轮换工作区码不会让它断线。',
+ 'onboard.securityTitle': '工作区配对码安全',
+ 'onboard.securityHelp': '如果怀疑配对码泄露,请先轮换,再检查计算机列表并移除可疑设备。移除计算机只会撤销该设备,不会轮换工作区配对码。如果轮换超时,请点“添加一台计算机”读取当前码,不会再次轮换。',
+ 'onboard.rotate': '配对码可能泄露?重新生成',
+ 'onboard.rotating': '正在生成…',
+ 'onboard.rotateConfirm': '要生成新的工作区配对码吗?旧码对应的添加计算机命令将失效,已配对的计算机会继续运行。完成后请检查计算机列表,确认没有不认识的设备。',
'onboard.engine': '引擎',
'onboard.engineHint': '只是默认值 —— 这台机器仍然可以在任何检测到的引擎上跑智能体',
'onboard.background': '让它在后台保持运行',
@@ -1289,14 +1294,14 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'me.hideAction': '收起',
'me.reconnect': '重新连接',
'me.remove': '移除',
- 'me.removeConfirm': '移除「{label}」?它上面的智能体会离线,直到你重新配对。',
- 'me.repairHint': '在「{name}」上跑这条命令以重连 —— 智能体仍会跟着。这个 token 长期有效。',
+ 'me.removeConfirm': '移除「{label}」?它上面的智能体会离线,直到你重新配对。此操作只撤销这台设备,不会轮换工作区配对码。',
+ 'me.repairHint': '在「{name}」上运行这条单机重连命令 —— 智能体仍会跟着。此码与用于添加计算机的工作区配对码相互独立。',
'me.copyCommand': '复制命令',
'me.copied': '✓ 已复制!',
'me.copy': '复制',
'me.copiedShort': '✓ 已复制',
'me.runOnHost': '在想要托管智能体的机器上跑这条命令:',
- 'me.engineRequired': '需要装好 <span class="font-mono not-italic">claude</span>、<span class="font-mono not-italic">codex</span>、<span class="font-mono not-italic">grok</span>、<span class="font-mono not-italic">cursor-agent</span> 或 <span class="font-mono not-italic">opencode</span>。计算机会以那台机器命名,配对后出现在这里。这个令牌长期有效。',
+ 'me.engineRequired': '需要装好 <span class="font-mono not-italic">claude</span>、<span class="font-mono not-italic">codex</span>、<span class="font-mono not-italic">grok</span>、<span class="font-mono not-italic">cursor-agent</span> 或 <span class="font-mono not-italic">opencode</span>。这是用于添加计算机的工作区配对码,除非轮换,否则一直有效。重连已有计算机时请使用该设备专用的重连码。',
'me.keepInBackground': '让它在后台保持运行',
'me.keepInBackgroundDetail': '—— 登录自启、崩溃自恢复、自动更新。否则这个终端就得一直开着。',
'me.done': '完成',
@@ -1515,6 +1520,16 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'workspace.roleMember': '成员',
'workspace.removeBtn': '移除',
'workspace.removeConfirm': '确定将 {name} 移出此工作区吗?对方会立即失去访问权限,但历史消息会保留。',
+ 'workspace.pairingCodeTitle': '计算机配对码',
+ 'workspace.pairingCodeHelp': '工作区配对码用于添加计算机;每台计算机另有独立的重连码。轮换只会使旧工作区码失效,已配对计算机和重连码仍有效。移除计算机只会撤销该设备,不会轮换工作区码。轮换后请检查计算机列表,并单独移除可疑设备。',
+ 'workspace.rotatePairingCodeConfirm': '要生成新的工作区配对码吗?旧码对应的添加命令将失效,已配对的计算机会继续运行。完成后请检查计算机列表。',
+ 'workspace.rotatePairingCode': '生成新配对码',
+ 'workspace.rotatingPairingCode': '正在轮换…',
+ 'workspace.showPairingCode': '显示当前码',
+ 'workspace.pairingCodeLoading': '正在加载…',
+ 'workspace.currentPairingCode': '当前工作区配对码',
+ 'workspace.pairingCodeUseFlow': '如需配对计算机,请前往“我 → 计算机”复制添加计算机命令。',
+ 'workspace.pairingCodeWrongWorkspace': '请先切换回此工作区,再查看或更改它的配对码。',
'workspace.dangerTitle': '删除工作区',
'workspace.deleteHelp': '永久删除此工作区及其中的会话、智能体、文档、看板、日历数据和附件。此操作无法撤销。',
'workspace.onlyWorkspace': '不能删除唯一的工作区。请先创建或加入另一个工作区。',
diff --git a/src/stores/auth.ts b/src/stores/auth.ts
index 95e9f72..1800abc 100644
--- a/src/stores/auth.ts
+++ b/src/stores/auth.ts
@@ -6,6 +6,7 @@
import { create } from 'zustand'
import type { ServerCapabilities } from '@/api/client'
import { commitIfEpochCurrent } from './contextEpoch'
+import { usePairingCodes } from './pairing-codes'
export interface AuthCompany {
id: string
@@ -71,6 +72,8 @@ export const useAuth = create<AuthState>((set) => ({
ready: false,
serverCapabilities: null,
setSession(token, user, companyId) {
+ // A fresh session must never inherit a code revealed by the previous one.
+ usePairingCodes.getState().clear()
localStorage.setItem(TOKEN_KEY, token)
if (companyId) localStorage.setItem(COMPANY_KEY, companyId)
set((s) => ({ token, user, activeCompanyId: companyId, ready: true, contextEpoch: s.contextEpoch + 1 }))
@@ -89,7 +92,11 @@ export const useAuth = create<AuthState>((set) => ({
: (activeCompanyId && memberIds.has(activeCompanyId) ? activeCompanyId : (companies[0]?.id ?? null))
if (resolved) localStorage.setItem(COMPANY_KEY, resolved)
else localStorage.removeItem(COMPANY_KEY)
- const previous = useAuth.getState().activeCompanyId
+ const previousState = useAuth.getState()
+ const previous = previousState.activeCompanyId
+ if (previousState.user?.id !== user.id || previous !== resolved) {
+ usePairingCodes.getState().clear()
+ }
set((s) => ({
user,
companies,
@@ -105,6 +112,7 @@ export const useAuth = create<AuthState>((set) => ({
},
setActiveCompany(id) {
if (useAuth.getState().activeCompanyId === id) return
+ usePairingCodes.getState().clear()
localStorage.setItem(COMPANY_KEY, id)
set((s) => ({ activeCompanyId: id, contextEpoch: s.contextEpoch + 1 }))
// Force the WS connection to re-handshake. The bridge filters events
@@ -122,6 +130,7 @@ export const useAuth = create<AuthState>((set) => ({
/** Append a freshly-created company to the user's set and switch to it. */
addCompany(c) {
const prevId = useAuth.getState().activeCompanyId
+ if (prevId !== c.id) usePairingCodes.getState().clear()
set((s) => ({
companies: [...s.companies, c],
activeCompanyId: c.id,
@@ -146,6 +155,7 @@ export const useAuth = create<AuthState>((set) => ({
const resolved = nextCompanyId && memberIds.has(nextCompanyId)
? nextCompanyId
: (companies[0]?.id ?? null)
+ usePairingCodes.getState().clear()
if (resolved) localStorage.setItem(COMPANY_KEY, resolved)
else localStorage.removeItem(COMPANY_KEY)
set((state) => ({
@@ -157,6 +167,7 @@ export const useAuth = create<AuthState>((set) => ({
return true
},
clear() {
+ usePairingCodes.getState().clear()
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(COMPANY_KEY)
set((s) => ({
diff --git a/src/stores/pairing-codes.ts b/src/stores/pairing-codes.ts
new file mode 100644
index 0000000..6d2bf05
--- /dev/null
+++ b/src/stores/pairing-codes.ts
@@ -0,0 +1,38 @@
+import { create } from 'zustand'
+
+/** The active workspace pairing code stays in renderer memory only. A single
+ * monotonically increasing request version rejects results from stale reads
+ * and rotations after logout, account changes, or workspace switches. */
+interface PairingCodesState {
+ companyId: string | null
+ code: string | null
+ requestVersion: number
+ beginRequest: (companyId: string, clearCode?: boolean) => number
+ setCodeIfCurrent: (companyId: string, requestVersion: number, code: string) => void
+ clear: () => void
+}
+
+export const usePairingCodes = create<PairingCodesState>((set, get) => ({
+ companyId: null,
+ code: null,
+ requestVersion: 0,
+ beginRequest: (companyId, clearCode = false) => {
+ const requestVersion = get().requestVersion + 1
+ set((state) => ({
+ companyId,
+ code: clearCode || state.companyId !== companyId ? null : state.code,
+ requestVersion,
+ }))
+ return requestVersion
+ },
+ setCodeIfCurrent: (companyId, requestVersion, code) => {
+ const state = get()
+ if (state.companyId !== companyId || state.requestVersion !== requestVersion) return
+ set({ code })
+ },
+ clear: () => set((state) => ({
+ companyId: null,
+ code: null,
+ requestVersion: state.requestVersion + 1,
+ })),
+}))
diff --git a/tests/pairing-codes-store.test.ts b/tests/pairing-codes-store.test.ts
new file mode 100644
index 0000000..ae7174a
--- /dev/null
+++ b/tests/pairing-codes-store.test.ts
@@ -0,0 +1,79 @@
+import assert from 'node:assert/strict'
+import { after, before, mock, test } from 'node:test'
+import { fileURLToPath } from 'node:url'
+import { createServer, type ViteDevServer } from 'vite'
+
+let server: ViteDevServer
+let auth: typeof import('../src/stores/auth')
+let pairingCodes: typeof import('../src/stores/pairing-codes')['usePairingCodes']
+let api: typeof import('../src/api/client')['api']
+const storageDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
+
+before(async () => {
+ const storage = new Map<string, string>()
+ Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: {
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => storage.set(key, value),
+ removeItem: (key: string) => storage.delete(key),
+ } })
+ server = await createServer({
+ configFile: false,
+ root: fileURLToPath(new URL('..', import.meta.url)),
+ resolve: { alias: { '@': fileURLToPath(new URL('../src', import.meta.url)) } },
+ server: { middlewareMode: true, watch: null },
+ appType: 'custom',
+ })
+ auth = await server.ssrLoadModule('/src/stores/auth.ts') as typeof auth
+ pairingCodes = (await server.ssrLoadModule('/src/stores/pairing-codes.ts')).usePairingCodes
+ const client = await server.ssrLoadModule('/src/api/client.ts')
+ api = client.api
+ mock.method(client.ws, 'reconnect', () => {})
+ mock.method(client.ws, 'close', () => {})
+})
+
+after(async () => {
+ mock.restoreAll()
+ await server?.close()
+ if (storageDescriptor) Object.defineProperty(globalThis, 'localStorage', storageDescriptor)
+ else Reflect.deleteProperty(globalThis, 'localStorage')
+})
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+test('a rotation response arriving after logout cannot restore the workspace code', async () => {
+ auth.useAuth.getState().clear()
+ auth.useAuth.getState().setMe(
+ { id: 'user-a', email: '[email protected]', name: 'User A' },
+ [{ id: 'company-a', name: 'Workspace A', slug: 'workspace-a', role: 'owner' }],
+ 'company-a',
+ )
+
+ const initialVersion = pairingCodes.getState().beginRequest('company-a')
+ pairingCodes.getState().setCodeIfCurrent('company-a', initialVersion, 'old-code')
+
+ const response = deferred<{ code: string; expiresInSeconds: null }>()
+ const stub = mock.method(api, 'rotatePairingCode', () => response.promise)
+ const rotation = async () => {
+ const targetCompanyId = auth.useAuth.getState().activeCompanyId!
+ const requestVersion = pairingCodes.getState().beginRequest(targetCompanyId, true)
+ const result = await api.rotatePairingCode()
+ pairingCodes.getState().setCodeIfCurrent(targetCompanyId, requestVersion, result.code)
+ }
+
+ try {
+ const pendingRotation = rotation()
+ assert.equal(pairingCodes.getState().code, null)
+ auth.useAuth.getState().clear()
+ response.resolve({ code: 'new-code', expiresInSeconds: null })
+ await pendingRotation
+
+ assert.equal(pairingCodes.getState().companyId, null)
+ assert.equal(pairingCodes.getState().code, null)
+ } finally {
+ stub.mock.restore()
+ }
+})