Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(dev): reuse pairing across ports and worktrees #8593

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromt3code/persistent-tailscale-pairingopened View on GitHub

Contributors repeatedly pair the same browser when Tailscale-hosted dev servers change ports or worktrees on one hostname. Cookie names, signing keys, and session records are currently worktree-local.

The web/server dev runner now defaults to ~/.t3/dev-auth. Servers in this group share a directory-scoped cookie name and sessions-v1.sqlite, containing only session records and the signing key. SQLite selects one complete key when processes start together. The auth schema is versioned separately, without app migrations.

Worktree databases, environment IDs, other secrets, and pairing grants stay local. Production and desktop auth do not change. Auth CLI commands read the target runtime metadata.

Risks and limits

  • Authentication is shared across participating dev servers. Browser, bearer, and DPoP sessions retain their scopes across the group. Worktree access is not isolated. Only direct browser connections get automatic cookie reuse.
  • --isolated-auth restores separate auth. T3CODE_DEV_AUTH_DIR selects another group. Neither protects against malicious branch code running as the same OS user.
  • Existing credentials do not migrate, so each browser needs one initial pairing. Cookies remain specific to each hostname and browser profile. Browser sessions last 30 days, DPoP sessions one hour. Native and added remote connections still pair per environment.
  • Revocation applies at the next authentication. Open WebSockets are not forcibly disconnected, and live connection status stays process-local.
  • An open tab must reload when another environment replaces its URL. The RPC identity check rejects that mismatch before readiness.
  • Offline auth commands without runtime metadata need T3CODE_DEV_AUTH_DIR and --dev-url. See dev auth.

Verification

After rebase, all 231 focused tests passed again: 90 server, 74 scripts, 49 client runtime, and 18 web auth. All three scoped typechecks, targeted lint/format checks, and git diff --check passed. Typechecks reported only pre-existing suggestions. Two Node processes shared a fresh database, key, and session. No browser or Tailscale end-to-end test was run.

Written by GPT-5.6 Sol in the Codex harness through T3 Code.


Note

High Risk Changes authentication storage, signing keys, and session sharing in development; misconfiguration could widen session reuse across dev servers on the same machine.

Overview Shared dev browser sessions so one pairing works across parallel web dev servers on the same host (different ports/worktrees) without cookie clashes.

Web dev with VITE_DEV_SERVER_URL can set T3CODE_DEV_AUTH_DIR (dev runner defaults to ~/.t3/dev-auth). SessionStore then uses new DevSessionStorage: a shared SQLite file (sessions-v1.sqlite) for session rows and a single signing key, with restrictive file permissions. Otherwise behavior stays per-worktree via the local DB and ServerSecretStore.

Cookie naming switches from port/instance scoping to a t3_session_dev_<hash> name derived from the auth directory when shared dev auth is active; desktop and production paths are unchanged.

Config and tooling: devAuthDir is persisted in server-runtime.json, resolveCliAuthConfig prefers that metadata for offline auth CLI, and the dev runner adds --isolated-auth to opt out. RPC reconnect now fails fast when the server’s environment ID no longer matches the tab’s prepared connection.

Pairing grants and per-worktree data stay local; only browser cookie transport gets automatic reuse within an auth group.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 864b1c0a344adcb3e2ec829ebd026f76994d8cd5. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add shared dev session storage across ports and worktrees

  • Adds DevSessionStorage, a shared SQLite-backed store for dev sessions and signing keys activated by devAuthDir.
  • Updates resolveSessionCookieName to use a shared dev cookie name derived from the devAuthDir.
  • Persists devAuthDir in runtime state and passes it to CLI pairing commands so they target the correct auth group.
  • Adds --isolated-auth to the dev runner to opt out of the default shared ~/.t3/dev-auth directory.
  • Behavioral Change: RpcSessionFactory.connect now rejects reused URLs serving a different environment with an environmentMismatchError. Active dev sessions may break if devAuthDir changes without clearing cookies.
📊 Macroscope summarized 864b1c0. 12 files reviewed, 1 issue evaluated, 0 issues filtered, 1 comment posted

🗂️ Filtered Issues

    1. Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: fdf747c6-d827-4f44-82f4-bb4d9edafde2

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. @@ -414,0 +413,21 @@
      413+ port: Option.none(),
      414+ host: Option.none(),
      415+ baseDir: flags.baseDir,
      416+ cwd: Option.none(),
      417+ devUrl: flags.devUrl ?? Option.none(),
      418+ noBrowser: Option.none(),
      419+ bootstrapFd: Option.none(),
      420+ autoBootstrapProjectFromCwd: Option.none(),
      421+ logWebSocketEvents: Option.none(),
      422+ tailscaleServeEnabled: Option.none(),
      423+ tailscaleServePort: Option.none(),
      424+ },
      425+ cliLogLevel,
      426+ );
      427+ const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
      428+ if (Option.isNone(runtimeState)) {
      429+ return config;
      430+ }
      431+
      432+ const { devAuthDir: _ambientDevAuthDir, ...configWithoutDevAuthDir } = config;
      433+ const targetDevUrl = runtimeState.value.devUrl ? new URL(runtimeState.value.devUrl) : undefined;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium cli/config.ts:433

      A syntactically invalid runtimeState.value.devUrl such as "not-a-url" throws at new URL(...), so resolveCliAuthConfig rejects and every auth CLI command targeting that state file fails instead of treating the runtime metadata as unavailable. Validate devUrl while decoding the persisted state (or catch this parse failure) so malformed runtime metadata follows the existing recovery path.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/cli/config.ts around line 433:
      
      A syntactically invalid `runtimeState.value.devUrl` such as `"not-a-url"` throws at `new URL(...)`, so `resolveCliAuthConfig` rejects and every auth CLI command targeting that state file fails instead of treating the runtime metadata as unavailable. Validate `devUrl` while decoding the persisted state (or catch this parse failure) so malformed runtime metadata follows the existing recovery path.
    4. Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.3 KiB13.3 KiB−67 B (−0.5%)15.1 KiB✅
      CodexThread snapshot wire6.9 KiB6.9 KiB−2 B (−0.0%)7.3 KiB✅
      CodexLive turn WebSocket wire6.4 KiB6.4 KiB−65 B (−1.0%)7.8 KiB✅
      CodexLive turn WebSocket decoded55.6 KiB55.5 KiB−88 B (−0.2%)66.4 KiB✅
      CodexLive turn messages119−2 (−18.2%)21✅
      ClaudeTotal thread wire13.3 KiB13.3 KiB+1 B (+0.0%)15.1 KiB✅
      ClaudeThread snapshot wire6.9 KiB6.9 KiB−1 B (−0.0%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.5 KiB6.5 KiB+2 B (+0.0%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded56.4 KiB56.4 KiB0 B (0.0%)66.4 KiB✅
      ClaudeLive turn messages11110 (0.0%)21✅

      Baseline: 22c311d · PR result: 864b1c0 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 109.4 KiB
      • Claude decoded thread snapshot: 110.1 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    5. Reviewed the new/changed Effect service code (DevSessionStorage, SessionStore, ServerConfig, CLI config, rpc/session). Imports, Foo["Service"] usage, and make/layer shapes follow the repository conventions. One error-modeling issue in the new dev session storage constructor.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +75,21 @@
      75+ "db.name": DATABASE_NAME,
      76+ "service.name": "t3-dev-auth",
      77+ },
      78+ });
      79+ const sqlContext = yield* Layer.build(sqlLayer);
      80+ const storage = yield* Effect.gen(function* () {
      81+ const sql = yield* SqlClient.SqlClient;
      82+ yield* setupSchema();
      83+
      84+ const candidate = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));
      85+ yield* sql`
      86+ INSERT INTO dev_auth_metadata (name, value)
      87+ VALUES (${SIGNING_SECRET_NAME}, ${candidate})
      88+ ON CONFLICT(name) DO NOTHING
      89+ `;
      90+ const rows = yield* sql<{ readonly value: unknown }>`
      91+ SELECT value AS "value"
      92+ FROM dev_auth_metadata
      93+ WHERE name = ${SIGNING_SECRET_NAME}
      94+ `;
      95+ const decodedRows = yield* decodeSigningSecretRows(rows);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      The raw SchemaError escapes into SessionStore.make's error channel here (the new test asserts _tag === "SchemaError"). Schema issue formatting renders the offending value, and that value is the session signing key, so a malformed row can put key material into a startup failure message. Every other reader of this table maps decode failures through PersistenceDecodeError.fromSchemaError, which keeps only the issue tags (see apps/server/src/persistence/Errors.ts and RepositoryErrorCorrelation.test.ts). The same applies to the bare SqlError from the surrounding statements, which AuthSessions wraps as PersistenceSqlError.

      Consider mapping the decode failure to the existing tagged persistence error (add import { PersistenceDecodeError } from "../persistence/Errors.ts"; and update the test expectation):

      -    const decodedRows = yield* decodeSigningSecretRows(rows);
      +    const decodedRows = yield* decodeSigningSecretRows(rows).pipe(
      +      Effect.mapError((cause) =>
      +        PersistenceDecodeError.fromSchemaError("DevSessionStorage.loadSigningSecret", cause),
      +      ),
      +    );
      Posted via Macroscope — Effect Service Conventions
    6. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 864b1c0a344adcb3e2ec829ebd026f76994d8cd5. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -340,3 +346,10 @@
      340346 delete output.T3CODE_HOME;
      341347 }
      342348
      349+ if (isDesktopMode || isolatedAuth === true) {
      350+ delete output.T3CODE_DEV_AUTH_DIR;
      351+ } else {
      352+ const configuredDevAuthDir = baseEnv.T3CODE_DEV_AUTH_DIR?.trim();
      353+ output.T3CODE_DEV_AUTH_DIR = configuredDevAuthDir
      354+ ? path.resolve(configuredDevAuthDir)
      355+ : yield* DEFAULT_DEV_AUTH_DIR;

      Dev runner skips home expansion

      Low Severity

      The dev runner resolves T3CODE_DEV_AUTH_DIR with path.resolve only, so a leading ~ becomes a cwd-relative directory. Server and CLI config expand ~ first. Because the runner writes the already-resolved value into the child environment, a quoted or dotenv ~/... path can place each worktree in a different auth group instead of the intended shared directory.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 864b1c0a344adcb3e2ec829ebd026f76994d8cd5. Configure [here](https://www.cursor.com/dashboard/bugbot).
    7. Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR introduces default-on shared development authentication, including persistent signing keys and session records, changed cookie behavior, and cross-environment connection handling. The authentication-sensitive scope and unresolved concerns around malformed metadata, error disclosure, and path normalization warrant human review.

      Not approved because:

      • 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).

Sign in to join this conversation.