Skip to content

Commit 23b5502

Browse files
t3dotggclaude
andauthored
feat(dev): Make t3 code dev instances shareable over Tailscale (#4556)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent a17cbc3 commit 23b5502

29 files changed

Lines changed: 1417 additions & 65 deletions

‎.agents/skills/test-t3-app/SKILL.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,17 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
1313
2. Choose a base directory that belongs only to the current worktree or test:
1414
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
1515
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
16-
3. Start the full web stack with `vp run dev`. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
16+
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
1717
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
1818

1919
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
2020

2121
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
2222

23+
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
24+
25+
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
26+
2327
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
2428

2529
## Preserve the environment while iterating

‎AGENTS.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
## Dev Servers
1717

1818
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
19+
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
20+
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
21+
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
1922

2023
## Package Roles
2124

‎apps/server/src/auth/EnvironmentAuth.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
88
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
99
import * as PairingGrantStore from "./PairingGrantStore.ts";
1010
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
11+
import { resolveSessionCookieName } from "./utils.ts";
1112

1213
import * as ServerSecretStore from "./ServerSecretStore.ts";
1314

15+
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
16+
const TEST_SERVER_PORT = 13_773;
17+
1418
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
1519
Layer.effect(
1620
ServerConfig.ServerConfig,
@@ -19,6 +23,12 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
1923
return {
2024
...config,
2125
...overrides,
26+
// Last, so the port cannot be overridden out from under
27+
// makeCookieRequest — which builds the cookie name from this constant.
28+
// An override that changed it would leave the server reading
29+
// t3_session_<other> while every request still sent t3_session_13773,
30+
// and the tests would fail for a reason unrelated to what they assert.
31+
port: TEST_SERVER_PORT,
2232
} satisfies ServerConfig.ServerConfig["Service"];
2333
}),
2434
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
@@ -35,7 +45,11 @@ const makeCookieRequest = (
3545
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
3646
({
3747
cookies: {
38-
t3_session: sessionToken,
48+
// Derived, not hardcoded: the name is port-scoped so concurrent servers
49+
// on one hostname don't share a cookie. Mode and devUrl mirror
50+
// ServerConfig.layerTest, so this resolves to whatever the server reads.
51+
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
52+
sessionToken,
3953
},
4054
headers: {},
4155
}) as unknown as Parameters<

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
438438
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
439439
readonly subject?: string;
440440
readonly proofKeyThumbprint?: string;
441+
readonly purpose?: "startup";
441442
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
442443
readonly issuePairingCredential: (
443444
input?: AuthCreatePairingCredentialInput,
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
746747
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
747748
readonly subject: string;
748749
readonly label?: string;
750+
readonly purpose?: "startup";
749751
}) =>
750752
createPairingLink({
751753
scopes: input.scopes,
752754
subject: input.subject,
753755
...(input.label ? { label: input.label } : {}),
756+
...(input.purpose ? { purpose: input.purpose } : {}),
754757
}).pipe(
755758
Effect.map(
756759
(issued) =>
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
774777
...(input?.ttl ? { ttl: input.ttl } : {}),
775778
...(input?.label ? { label: input.label } : {}),
776779
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
780+
...(input?.purpose ? { purpose: input.purpose } : {}),
777781
});
778782
return {
779783
id: issued.id,
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
872876
issuePairingCredentialForSubject({
873877
scopes: AuthAdministrativeScopes,
874878
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
879+
purpose: "startup",
875880
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
876881

877882
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>

‎apps/server/src/auth/EnvironmentAuthPolicy.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
3434

3535
expect(descriptor.policy).toBe("desktop-managed-local");
3636
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
37+
// Packaged desktop has no devUrl, but still needs the port scope: it
38+
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
39+
// instance shares this one's hostname on a different port.
3740
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
3841
}).pipe(
3942
Effect.provide(
@@ -45,6 +48,22 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
4548
),
4649
);
4750

51+
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
52+
Effect.gen(function* () {
53+
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
54+
const descriptor = yield* policy.getDescriptor();
55+
56+
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
57+
}).pipe(
58+
Effect.provide(
59+
makeEnvironmentAuthPolicyLayer({
60+
mode: "desktop",
61+
port: 3774,
62+
}),
63+
),
64+
),
65+
);
66+
4867
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
4968
Effect.gen(function* () {
5069
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
@@ -75,6 +94,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
7594
makeEnvironmentAuthPolicyLayer({
7695
mode: "web",
7796
host: "127.0.0.1",
97+
port: 13773,
98+
}),
99+
),
100+
),
101+
);
102+
103+
it.effect("scopes web session cookies by port only in development", () =>
104+
Effect.gen(function* () {
105+
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
106+
const descriptor = yield* policy.getDescriptor();
107+
108+
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
109+
}).pipe(
110+
Effect.provide(
111+
makeEnvironmentAuthPolicyLayer({
112+
mode: "web",
113+
port: 13773,
114+
devUrl: new URL("http://127.0.0.1:5733"),
78115
}),
79116
),
80117
),

‎apps/server/src/auth/EnvironmentAuthPolicy.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export const make = Effect.gen(function* () {
4141
sessionCookieName: resolveSessionCookieName({
4242
mode: config.mode,
4343
port: config.port,
44+
devUrl: config.devUrl,
4445
}),
4546
};
4647

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
202202
readonly subject?: string;
203203
readonly label?: string;
204204
readonly proofKeyThumbprint?: string;
205+
/**
206+
* "startup" marks the credential the server mints for itself at boot,
207+
* which gets the long dev TTL when a dev URL is configured.
208+
*/
209+
readonly purpose?: "startup";
205210
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
206211
readonly listActive: () => Effect.Effect<
207212
ReadonlyArray<AuthPairingLink>,
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
243248
// window can still recover by re-bootstrapping rather than locking
244249
// the user out of the backend.
245250
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
251+
// A dev server's startup token is read off a log by whoever (or whatever) is
252+
// driving the session, often minutes later — after a `node --watch` restart, a
253+
// detour into another task, or a hand-off to the person actually doing the
254+
// testing. Five minutes turns that into a restart-the-server loop for no
255+
// security benefit: the token only unlocks a local dev backend, and its holder
256+
// could read the log anyway. Same reasoning (and duration) as the desktop
257+
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
258+
// pairing links and real servers keep the 5-minute default.
259+
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
246260
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
247261
const PAIRING_TOKEN_LENGTH = 12;
248262
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
371385
),
372386
);
373387
const credential = yield* generatePairingToken;
374-
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
388+
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
389+
const ttl =
390+
input?.ttl ??
391+
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
375392
const now = yield* DateTime.now;
376393
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
377394
const issued: IssuedBootstrapCredential = {

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,7 @@ export const make = Effect.gen(function* () {
470470
const cookieName = resolveSessionCookieName({
471471
mode: serverConfig.mode,
472472
port: serverConfig.port,
473+
devUrl: serverConfig.devUrl,
473474
});
474475

475476
const emitUpsert = (clientSession: AuthClientSession) =>

‎apps/server/src/auth/utils.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,29 @@ import * as Result from "effect/Result";
1010

1111
const SESSION_COOKIE_NAME = "t3_session";
1212

13+
/**
14+
* Cookies are scoped by host but *not* by port, so any two servers that can be
15+
* live on one hostname at once need separate names — otherwise the second
16+
* clobbers the first's session and both sides see "Invalid session token
17+
* signature" until someone clears cookies by hand.
18+
*
19+
* Two populations qualify, for the same reason but from different causes:
20+
*
21+
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
22+
* - **Desktop**, which scans upward from 3773 for a free port and binds
23+
* 127.0.0.1, so a second instance lands on a different port and the same host.
24+
*
25+
* Hosted deployments keep the stable production name: their public port can
26+
* change between releases, and scoping it would log every user out.
27+
*/
1328
export function resolveSessionCookieName(input: {
1429
readonly mode: "web" | "desktop";
1530
readonly port: number;
31+
readonly devUrl: URL | undefined;
1632
}): string {
17-
if (input.mode !== "desktop") {
18-
return SESSION_COOKIE_NAME;
19-
}
20-
21-
return `${SESSION_COOKIE_NAME}_${input.port}`;
33+
return input.devUrl === undefined && input.mode !== "desktop"
34+
? SESSION_COOKIE_NAME
35+
: `${SESSION_COOKIE_NAME}_${input.port}`;
2236
}
2337

2438
export function base64UrlEncode(input: string | Uint8Array): string {

‎apps/server/src/bin.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
8484
...derivedPaths,
8585
staticDir: undefined,
8686
devUrl: undefined,
87+
devAllowedOrigins: [],
8788
noBrowser: true,
8889
startupPresentation: "browser",
8990
desktopBootstrapToken: undefined,

0 commit comments

Comments
 (0)