Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(desktop): keep the dev Clerk key out of child processes and tighten the test account flow

leepokai390b7aee6e48
diff --git a/apps/desktop/src/main/account.ts b/apps/desktop/src/main/account.ts
index 63cae5c3..1a625e5c 100644
--- a/apps/desktop/src/main/account.ts
+++ b/apps/desktop/src/main/account.ts
@@ -137,7 +137,7 @@ export class AccountService extends EventEmitter {
/** An unpackaged Codync Dev run with a test account's one-time sign-in token (tools/dev-account.mjs): signs in without a browser. */
private async signInWithDevTicket() {
const ticket = process.env.CODYNC_DEV_SIGN_IN_TICKET
- if (!ticket || app.isPackaged || identity.environment !== 'dev' || this.activeSession) return
+ if (!ticket || app.isPackaged || identity.environment !== 'dev' || !this.config.clerkPublishableKey?.startsWith('pk_test_') || this.activeSession) return
try {
await this.request<SignInResource>('POST', '/v1/client/sign_ins', { strategy: 'ticket', ticket })
await this.refreshClient()
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index c04f3d34..333d492a 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -156,9 +156,12 @@ function registerIPC(tray: Tray) {
ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))
ipcMain.on('app:computerName', (e) => (e.returnValue = computerName()))
ipcMain.on('app:openedAtLogin', (e) => (e.returnValue = openedAtLogin()))
+ // `reset` is answered once per start, so a reload or another window doesn't bring the welcome flow back mid-session.
+ let onboardingReset = false
ipcMain.on('app:devOnboarding', (e) => {
const mode = process.env.CODYNC_DEV_ONBOARDING
- e.returnValue = !app.isPackaged && identity.environment === 'dev' && (mode === 'skip' || mode === 'reset') ? mode : null
+ const dev = !app.isPackaged && identity.environment === 'dev'
+ e.returnValue = dev && mode === 'skip' ? 'skip' : dev && mode === 'reset' && !onboardingReset ? ((onboardingReset = true), 'reset') : null
})
ipcMain.on('app:debugOpen', (e) => (e.returnValue = app.isPackaged ? null : (process.env.CODYNC_DEBUG_OPEN ?? null)))
ipcMain.handle('host:snapshot', () => snapshot())
diff --git a/apps/desktop/src/shared/dev-sandbox.test.ts b/apps/desktop/src/shared/dev-sandbox.test.ts
index 972b5a4e..27c74fbe 100644
--- a/apps/desktop/src/shared/dev-sandbox.test.ts
+++ b/apps/desktop/src/shared/dev-sandbox.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { sandboxLabel, sandboxName, sandboxPorts } from './dev-sandbox.ts'
+import { devClerkSecretKey, sandboxLabel, sandboxName, sandboxPorts } from './dev-sandbox.ts'
test('sandbox ports skip the ones other sandboxes hold and never reach Codync or Codync Dev', () => {
const ports = sandboxPorts([19300, 19302])
@@ -14,3 +14,12 @@ test('a sandbox is named after its worktree folder', () => {
assert.equal(sandboxLabel('Codync Dev', '/Users/me/.codync-dev-feat-x'), 'Codync Dev (feat-x)')
assert.equal(sandboxLabel('Codync Dev', 'C:\\Users\\me\\box\\'), 'Codync Dev (box)')
})
+
+test('a sandbox only ever takes a Clerk development key, from the environment first', () => {
+ assert.equal(devClerkSecretKey(undefined, undefined), null)
+ assert.equal(devClerkSecretKey(undefined, 'OTHER=1\nCODYNC_CLERK_SECRET_KEY="sk_test_abc"\n'), 'sk_test_abc')
+ assert.equal(devClerkSecretKey(' sk_test_env ', 'CODYNC_CLERK_SECRET_KEY=sk_test_file'), 'sk_test_env')
+ assert.equal(devClerkSecretKey(undefined, 'CLERK_SECRET_KEY=sk_live_other'), null)
+ assert.throws(() => devClerkSecretKey('sk_live_x', undefined), /sk_test_/)
+ assert.throws(() => devClerkSecretKey(undefined, 'CODYNC_CLERK_SECRET_KEY=sk_live_x'), /sk_test_/)
+})
diff --git a/apps/desktop/src/shared/dev-sandbox.ts b/apps/desktop/src/shared/dev-sandbox.ts
index c8ec4c44..596f1332 100644
--- a/apps/desktop/src/shared/dev-sandbox.ts
+++ b/apps/desktop/src/shared/dev-sandbox.ts
@@ -12,6 +12,14 @@ export function sandboxPorts(claimed: Iterable<number>): number[] {
return Array.from({ length: 100 }, (_, i) => 19300 + i).filter((port) => !taken.has(port))
}
+/** The Clerk development secret key a sandbox may use: the environment's, else the `.env` file's `CODYNC_CLERK_SECRET_KEY`; null when neither is set. Anything but an `sk_test_` key throws, so production is never reached. */
+export function devClerkSecretKey(fromEnv: string | undefined, envFile: string | undefined) {
+ const raw = fromEnv ?? /^CODYNC_CLERK_SECRET_KEY=(.+)$/m.exec(envFile ?? '')?.[1] ?? ''
+ const key = raw.trim().replace(/^["']|["']$/g, '')
+ if (key && !key.startsWith('sk_test_')) throw new Error('CODYNC_CLERK_SECRET_KEY must be the development instance key (sk_test_...).')
+ return key || null
+}
+
/** `Codync Dev (feat-x)` for `~/.codync-dev-feat-x`; any other host data folder shows by its name. */
export function sandboxLabel(name: string, home: string) {
const folder = home.split(/[\\/]/).filter(Boolean).pop() ?? home
diff --git a/apps/desktop/tools/dev-account.mjs b/apps/desktop/tools/dev-account.mjs
index fd1116f4..89cc734d 100644
--- a/apps/desktop/tools/dev-account.mjs
+++ b/apps/desktop/tools/dev-account.mjs
@@ -1,23 +1,22 @@
// A Clerk test account for `npm run dev` sandboxes: finds or creates `sandbox-<name>[email protected]`
// in the Clerk *development* instance and mints a one-time sign-in token the app trades for a session
-// (account.ts, `CODYNC_DEV_SIGN_IN_TICKET`). The secret key comes from CLERK_SECRET_KEY or the git-ignored
+// (account.ts, `CODYNC_DEV_SIGN_IN_TICKET`). The secret key comes from CODYNC_CLERK_SECRET_KEY or the git-ignored
// `.env` in the main checkout's root (every worktree reads that one file); only `sk_test_` keys are used,
// so production is never touched.
import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { devClerkSecretKey } from '../src/shared/dev-sandbox.ts'
const API = 'https://api.clerk.com/v1'
export function secretKey() {
// A linked worktree's git common dir is the main checkout's `.git`, so its parent holds the shared `.env`.
- const common = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd: dirname(fileURLToPath(import.meta.url)), encoding: 'utf8' }).stdout.trim()
- const file = resolve(dirname(fileURLToPath(import.meta.url)), common, '..', '.env')
- const fromFile = existsSync(file) ? /^CLERK_SECRET_KEY=(.+)$/m.exec(readFileSync(file, 'utf8'))?.[1] : undefined
- const key = (process.env.CLERK_SECRET_KEY ?? fromFile ?? '').trim().replace(/^["']|["']$/g, '')
- if (key && !key.startsWith('sk_test_')) throw new Error('CLERK_SECRET_KEY must be the development instance key (sk_test_...).')
- return key || null
+ const here = dirname(fileURLToPath(import.meta.url))
+ const git = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd: here, encoding: 'utf8' })
+ const file = git.status === 0 ? resolve(here, git.stdout.trim(), '..', '.env') : null
+ return devClerkSecretKey(process.env.CODYNC_CLERK_SECRET_KEY, file && existsSync(file) ? readFileSync(file, 'utf8') : undefined)
}
async function clerk(key, method, path, body) {
diff --git a/apps/desktop/tools/dev.mjs b/apps/desktop/tools/dev.mjs
index 348a57d2..5df7eb2e 100644
--- a/apps/desktop/tools/dev.mjs
+++ b/apps/desktop/tools/dev.mjs
@@ -15,7 +15,7 @@ import { basename, dirname, join, resolve } from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
import { parseArgs } from 'node:util'
-import { deleteTestAccount, mintTicket } from './dev-account.mjs'
+import { deleteTestAccount, mintTicket, secretKey } from './dev-account.mjs'
import { SANDBOX_PREFIX, sandboxName, sandboxPorts } from '../src/shared/dev-sandbox.ts'
const desktop = resolve(dirname(fileURLToPath(import.meta.url)), '..')
@@ -28,6 +28,12 @@ const { values: flags } = parseArgs({
},
})
+/** The environment for the host and the app: the Clerk secret key stays in this script, since the host hands its environment to every agent it runs. */
+function childEnv() {
+ const { CODYNC_CLERK_SECRET_KEY: _key, ...env } = process.env
+ return env
+}
+
function fail(message) {
console.error(message)
process.exit(1)
@@ -97,11 +103,12 @@ async function listAndPrune() {
account = await deleteTestAccount(s.name)
} catch (e) {
// The sandbox folder is how a later --prune finds the account again.
- console.error(`Kept the sandbox ${s.name}: its Clerk test account wasn't deleted (${e.message}). Run --prune again.`)
+ console.error(`Kept the sandbox ${s.name}: its Clerk test account wasn't deleted (${e.message}). Fix that, then run --prune again.`)
continue
}
rmSync(s.home, { recursive: true, force: true })
console.log(`Deleted the sandbox ${s.name} (${s.home})${account ? ' and its Clerk test account' : ''}`)
+ if (!account && !secretKey()) console.log(` Without CODYNC_CLERK_SECRET_KEY its Clerk test account stays; delete ${s.name}'s sandbox-*+clerk_test user in the Clerk dashboard.`)
} else if (flags.list) {
console.log(`${s.name.padEnd(28)} ${String(s.port).padEnd(6)} ${(running ? 'running' : 'stopped').padEnd(8)} ${s.worktree}${gone ? ' (gone)' : ''}`)
}
@@ -123,7 +130,7 @@ async function sandbox() {
const host = buildHost()
const log = join(home, 'host.log')
- const hostEnv = { ...process.env, CODYNC_HOME: home, ...(flags.cloud ? {} : { CODYNC_CLOUD: 'off' }) }
+ const hostEnv = { ...childEnv(), CODYNC_HOME: home, ...(flags.cloud ? {} : { CODYNC_CLOUD: 'off' }) }
const out = openSync(log, 'a')
const hostProcess = spawn(host, ['serve', '--port', String(port)], { env: hostEnv, stdio: ['ignore', out, out] })
hostProcess.on('error', (e) => fail(`Couldn't start ${host}: ${e.message}`))
@@ -158,17 +165,16 @@ async function sandbox() {
if (cdp) console.log(` DevTools protocol 127.0.0.1:${cdp}`)
console.log('')
const appEnv = {
- ...process.env, CODYNC_HOME: home, CODYNC_PORT: String(port),
+ ...childEnv(), CODYNC_HOME: home, CODYNC_PORT: String(port),
...(cdp ? { CODYNC_REMOTE_DEBUG: String(cdp) } : {}),
CODYNC_DEV_ONBOARDING: flags.onboarding ? 'reset' : 'skip',
}
- // The saved session lives in desktop/account.bin; a token is only needed while it is missing.
- if (!existsSync(join(home, 'desktop/account.bin'))) {
- const account = await mintTicket(name).catch((e) => console.error(`Test account skipped: ${e.message}`))
- if (account) {
- appEnv.CODYNC_DEV_SIGN_IN_TICKET = account.token
- console.log(` test account ${account.email}\n`)
- }
+ // The app trades the token only while it has no active session, so a signed-out or expired sandbox signs in again.
+ const account = await mintTicket(name).catch((e) => console.error(`Test account skipped: ${e.message}`))
+ if (stopping) return
+ if (account) {
+ appEnv.CODYNC_DEV_SIGN_IN_TICKET = account.token
+ console.log(` test account ${account.email}\n`)
}
app = startApp(appEnv)
app.child.on('exit', (code) => stop(code ?? 0))
diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.md
index 58220942..231c5478 100644
--- a/docs/guides/dev-app.md
+++ b/docs/guides/dev-app.md
@@ -30,7 +30,7 @@ Xcode configurations separate environment from optimization: `Debug` and `Releas
Flags go after `npm run dev --`: `--shared` takes the default Codync Dev from a worktree (quit the main checkout's first); `--sandbox` runs a sandbox from the main checkout, for a second session on `dev`; `--name <name>` runs the sandbox of that name, for another copy of the same checkout; `--cloud` lets the sandbox host use the dev cloud (each sandbox then shows as another computer); `--cdp` opens the DevTools protocol on the sandbox port + 10000; `--list` shows every sandbox; `--prune` deletes the ones whose worktree is gone (and their Clerk test accounts), so run it after removing worktrees.
-A sandbox starts past onboarding (welcome and computer-access setup, only where the window hasn't chosen yet); `--onboarding` clears those two settings at each start, so the flow comes back (a signed-in sandbox passes the welcome screen by itself and lands on computer-access setup). With `CLERK_SECRET_KEY` (the Clerk **development** instance's `sk_test_...` key) in the git-ignored `.env` at the main checkout's root (every worktree reads that one file) or the environment, it also signs in its own Clerk test account `sandbox-<name>[email protected]`: `tools/dev-account.mjs` finds or creates that user through the Backend API and mints a one-time sign-in token, which `account.ts` trades for a session (`ticket` strategy, unpackaged Dev runs only). The session stays in the sandbox's `desktop/`, so the token is minted only while `desktop/account.bin` is missing. Keys that aren't `sk_test_` are refused. Without a key a sandbox starts signed out; it never borrows Codync Dev's login.
+A sandbox starts past onboarding (welcome and computer-access setup, only where the window hasn't chosen yet); `--onboarding` clears those two settings once per start, so the flow comes back (a signed-in sandbox passes the welcome screen by itself and lands on computer-access setup). With `CODYNC_CLERK_SECRET_KEY` (the Clerk **development** instance's `sk_test_...` key) in the git-ignored `.env` at the main checkout's root (every worktree reads that one file) or the environment, it also signs in its own Clerk test account `sandbox-<name>[email protected]`: `tools/dev-account.mjs` finds or creates that user through the Backend API and mints a one-time sign-in token, which `account.ts` trades for a session (`ticket` strategy, unpackaged Dev runs only). The token is minted at every start and used only while the sandbox has no active session; the app also requires a `pk_test_` publishable key, and the key never reaches the host or the agents. Keys that aren't `sk_test_` are refused. Without a key a sandbox starts signed out; it never borrows Codync Dev's login.
Still shared: macOS sees every unpackaged run as the same Electron app, so permissions and notifications are shared and a `codync-dev://` sign-in callback may reach another copy (test sign-in on the default Codync Dev); Codync Screen and computer use need the packaged `Codync Dev.app`; a global shortcut (the approval island's) goes to whichever app registered it first.