Skip to content

Commit 3b75e60

Browse files
authored
feat(server): add reusable auth token for dev worktrees (pingdotgg#8606)
1 parent 5647191 commit 3b75e60

20 files changed

Lines changed: 1177 additions & 42 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
7979
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
8080
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
8181
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
82-
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
83-
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
82+
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, then give that full URL to an unpaired browser. Do not wire up `tailscale serve` by hand, open the URL yourself, or consume the user's pairing link. A browser with the reusable dev cookie can use the bare origin. If a normal one-time token was consumed, mint a fresh one with `node apps/server/src/bin.ts pair`. It carries standard scopes, while the startup URL carries admin scopes needed for Connections settings.
83+
- To reuse web dev auth across worktrees, configure one fixed `T3CODE_DEV_AUTH_TOKEN` in the main checkout's gitignored `.env`. The `t3.json` setup links that file into worktrees. Never commit or publish the token or a startup URL. See [Reusable dev credential](docs/operations/development.md#reusable-dev-credential).
8484
- Stop what you started, by the PID you tracked. See rule 1.
8585

8686
## Test data

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

Lines changed: 217 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import { AuthAdministrativeScopes } from "@t3tools/contracts";
33
import { expect, it } from "@effect/vitest";
44
import * as Effect from "effect/Effect";
55
import * as Layer from "effect/Layer";
6+
import * as Redacted from "effect/Redacted";
7+
import * as Schema from "effect/Schema";
8+
import * as SqlClient from "effect/unstable/sql/SqlClient";
69

710
import * as ServerConfig from "../config.ts";
811
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
12+
import * as PersistenceErrors from "../persistence/Errors.ts";
913
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
1014
import * as PairingGrantStore from "./PairingGrantStore.ts";
1115
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
@@ -15,6 +19,8 @@ import * as SessionStore from "./SessionStore.ts";
1519

1620
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
1721
const TEST_SERVER_PORT = 13_773;
22+
const isPairingCredentialIssueError = Schema.is(PairingGrantStore.PairingCredentialIssueError);
23+
const isPersistenceSqlError = Schema.is(PersistenceErrors.PersistenceSqlError);
1824

1925
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
2026
Layer.effect(
@@ -33,7 +39,7 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
3339

3440
const makeEnvironmentAuthLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
3541
EnvironmentAuth.layer.pipe(
36-
Layer.provide(SqlitePersistenceMemory),
42+
Layer.provideMerge(SqlitePersistenceMemory),
3743
Layer.provide(ServerSecretStore.layer),
3844
Layer.provide(ServerEnvironment.identityLayer),
3945
Layer.provide(makeServerConfigLayer(overrides)),
@@ -72,6 +78,216 @@ const requestMetadata = {
7278
};
7379

7480
it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
81+
it.effect("uses the reusable dev cookie without overriding a normal scoped cookie", () =>
82+
Effect.gen(function* () {
83+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
84+
const sessions = yield* SessionStore.SessionStore;
85+
const token = "reusable-dev-auth-token-that-is-long-enough";
86+
const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata);
87+
const pairing = yield* serverAuth.issuePairingCredential({ scopes: ["orchestration:read"] });
88+
const scopedExchange = yield* serverAuth.createBrowserSession(
89+
pairing.credential,
90+
requestMetadata,
91+
);
92+
const request = {
93+
cookies: {
94+
[sessions.cookieName]: scopedExchange.sessionToken,
95+
[devExchange.cookieName ?? "missing"]: devExchange.sessionToken,
96+
},
97+
headers: {},
98+
} as unknown as Parameters<
99+
EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]
100+
>[0];
101+
102+
const authenticated = yield* serverAuth.authenticateHttpRequest(request);
103+
expect(devExchange.cookieName).toMatch(/^t3_dev_session_/);
104+
expect(devExchange.expireNormalCookie).toBe(true);
105+
expect(authenticated.scopes).toEqual(["orchestration:read"]);
106+
}).pipe(
107+
Effect.provide(
108+
makeEnvironmentAuthLayer({
109+
mode: "web",
110+
devUrl: new URL("http://127.0.0.1:5173"),
111+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
112+
}),
113+
),
114+
),
115+
);
116+
117+
it.effect("does not fall back to the dev cookie after a normal cookie is rejected", () =>
118+
Effect.gen(function* () {
119+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
120+
const sessions = yield* SessionStore.SessionStore;
121+
const token = "reusable-dev-auth-token-that-is-long-enough";
122+
const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata);
123+
const pairing = yield* serverAuth.issuePairingCredential({ scopes: ["orchestration:read"] });
124+
const scopedExchange = yield* serverAuth.createBrowserSession(
125+
pairing.credential,
126+
requestMetadata,
127+
);
128+
const scoped = yield* sessions.verify(scopedExchange.sessionToken);
129+
yield* sessions.revoke(scoped.sessionId);
130+
const request = {
131+
cookies: {
132+
[sessions.cookieName]: scopedExchange.sessionToken,
133+
[devExchange.cookieName ?? "missing"]: devExchange.sessionToken,
134+
},
135+
headers: {},
136+
} as unknown as Parameters<
137+
EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]
138+
>[0];
139+
140+
const error = yield* Effect.flip(serverAuth.authenticateHttpRequest(request));
141+
expect(error._tag).toBe("ServerAuthInvalidCredentialError");
142+
}).pipe(
143+
Effect.provide(
144+
makeEnvironmentAuthLayer({
145+
mode: "web",
146+
devUrl: new URL("http://127.0.0.1:5173"),
147+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
148+
}),
149+
),
150+
),
151+
);
152+
153+
it.effect("does not use the dev cookie when Authorization is invalid or empty", () =>
154+
Effect.gen(function* () {
155+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
156+
const token = "reusable-dev-auth-token-that-is-long-enough";
157+
const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata);
158+
for (const authorization of ["Bearer invalid", ""] as const) {
159+
const request = {
160+
cookies: { [devExchange.cookieName ?? "missing"]: devExchange.sessionToken },
161+
headers: { authorization },
162+
} as unknown as Parameters<
163+
EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]
164+
>[0];
165+
const error = yield* Effect.flip(serverAuth.authenticateHttpRequest(request));
166+
expect(EnvironmentAuth.isServerAuthCredentialError(error)).toBe(true);
167+
}
168+
}).pipe(
169+
Effect.provide(
170+
makeEnvironmentAuthLayer({
171+
mode: "web",
172+
devUrl: new URL("http://127.0.0.1:5173"),
173+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
174+
}),
175+
),
176+
),
177+
);
178+
179+
it.effect("exchanges the reusable dev token for a local scoped OAuth session", () =>
180+
Effect.gen(function* () {
181+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
182+
const sessions = yield* SessionStore.SessionStore;
183+
const token = "reusable-dev-auth-token-that-is-long-enough";
184+
const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
185+
token,
186+
["orchestration:read"],
187+
requestMetadata,
188+
);
189+
190+
expect(exchanged.access_token).not.toBe(token);
191+
expect(exchanged.scope).toBe("orchestration:read");
192+
const dpop = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
193+
token,
194+
["orchestration:read"],
195+
requestMetadata,
196+
{ proofKeyThumbprint: "test-proof-key" },
197+
);
198+
expect(dpop.access_token).not.toBe(token);
199+
expect(dpop.access_token).not.toBe(exchanged.access_token);
200+
expect(dpop.token_type).toBe("DPoP");
201+
expect(dpop.scope).toBe("orchestration:read");
202+
203+
const secondBearer = yield* serverAuth.exchangeBootstrapCredentialForAccessToken(
204+
token,
205+
["orchestration:read"],
206+
requestMetadata,
207+
);
208+
const firstSession = yield* serverAuth.authenticateHttpRequest(
209+
makeBearerRequest(exchanged.access_token),
210+
);
211+
const secondSession = yield* serverAuth.authenticateHttpRequest(
212+
makeBearerRequest(secondBearer.access_token),
213+
);
214+
expect(firstSession.subject).toBe("reusable-dev-token-child");
215+
expect(secondSession.subject).toBe("reusable-dev-token-child");
216+
expect((yield* sessions.verify(token)).subject).toBe("reusable-dev-token");
217+
}).pipe(
218+
Effect.provide(
219+
makeEnvironmentAuthLayer({
220+
mode: "web",
221+
devUrl: new URL("http://127.0.0.1:5173"),
222+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
223+
}),
224+
),
225+
),
226+
);
227+
228+
it.effect("uses a one-time startup credential after local dev token revocation", () =>
229+
Effect.gen(function* () {
230+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
231+
const sessions = yield* SessionStore.SessionStore;
232+
const token = "reusable-dev-auth-token-that-is-long-enough";
233+
const initial = yield* serverAuth.issueStartupPairingCredential();
234+
const seeded = yield* sessions.verify(token);
235+
236+
yield* sessions.revoke(seeded.sessionId);
237+
const recovery = yield* serverAuth.issueStartupPairingCredential();
238+
239+
expect(initial.credential).toBe(token);
240+
expect(recovery.credential).not.toBe(token);
241+
expect((yield* Effect.flip(sessions.verify(token)))._tag).toBe("SessionTokenRevokedError");
242+
expect(
243+
(yield* serverAuth.createBrowserSession(recovery.credential, requestMetadata)).response,
244+
).toMatchObject({ authenticated: true, scopes: AuthAdministrativeScopes });
245+
}).pipe(
246+
Effect.provide(
247+
makeEnvironmentAuthLayer({
248+
mode: "web",
249+
devUrl: new URL("http://127.0.0.1:5173"),
250+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
251+
}),
252+
),
253+
),
254+
);
255+
256+
it.effect("keeps the pairing issue error as the immediate recovery failure", () =>
257+
Effect.gen(function* () {
258+
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
259+
const sessions = yield* SessionStore.SessionStore;
260+
const sql = yield* SqlClient.SqlClient;
261+
const token = "reusable-dev-auth-token-that-is-long-enough";
262+
const seeded = yield* sessions.verify(token);
263+
264+
yield* sessions.revoke(seeded.sessionId);
265+
yield* sql`
266+
CREATE TRIGGER reject_startup_pairing_link
267+
BEFORE INSERT ON auth_pairing_links
268+
BEGIN
269+
SELECT RAISE(ABORT, 'startup pairing insert rejected');
270+
END
271+
`;
272+
273+
const error = yield* Effect.flip(serverAuth.issueStartupPairingCredential());
274+
275+
expect(error._tag).toBe("ServerAuthPairingLinkCreationError");
276+
expect(isPairingCredentialIssueError(error.cause)).toBe(true);
277+
if (isPairingCredentialIssueError(error.cause)) {
278+
expect(isPersistenceSqlError(error.cause.cause)).toBe(true);
279+
}
280+
}).pipe(
281+
Effect.provide(
282+
makeEnvironmentAuthLayer({
283+
mode: "web",
284+
devUrl: new URL("http://127.0.0.1:5173"),
285+
devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"),
286+
}),
287+
),
288+
),
289+
);
290+
75291
it.effect("classifies invalid bootstrap credential failures for the HTTP boundary", () =>
76292
Effect.sync(() => {
77293
const error = EnvironmentAuth.toBootstrapExchangeError(

0 commit comments

Comments
 (0)