@devries-cameron20 / t3code-1 / commits / 2a29de7502
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

[codex] Structure primary auth validation failures (#3471)

Co-authored-by: codex <codex@users.noreply.github.com>

Julius Marminge committed Jun 20, 2026 at 20:20 UTC 2a29de7502cdd02686bda7d12fb2671060fd1979
4 files changed +146 -81
apps/web/src/authBootstrap.test.ts
+76 -26
@@ -71,6 +71,18 @@ function installTestBrowser(url: string) {
71 return testWindow;
72 }
73
74 +function installDesktopBootstrap() {
75 + const testWindow = installTestBrowser("http://localhost/");
76 + testWindow.desktopBridge = {
77 + getLocalEnvironmentBootstrap: () => ({
78 + label: "Local environment",
79 + httpBaseUrl: "http://localhost:3773",
80 + wsBaseUrl: "ws://localhost:3773",
81 + bootstrapToken: "desktop-bootstrap-token",
82 + }),
83 + } as DesktopBridge;
84 +}
85 +
86 function sequence<A>(...values: ReadonlyArray<A>) {
87 let index = 0;
88 return () => values[Math.min(index++, values.length - 1)]!;
@@ -131,15 +143,7 @@ describe("resolveInitialServerAuthGateState", () => {
143 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
144 });
145
134 - const testWindow = installTestBrowser("http://localhost/");
135 - testWindow.desktopBridge = {
136 - getLocalEnvironmentBootstrap: () => ({
137 - label: "Local environment",
138 - httpBaseUrl: "http://localhost:3773",
139 - wsBaseUrl: "ws://localhost:3773",
140 - bootstrapToken: "desktop-bootstrap-token",
141 - }),
142 - } as DesktopBridge;
146 + installDesktopBootstrap();
147
148 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
149
@@ -289,6 +293,23 @@ describe("resolveInitialServerAuthGateState", () => {
293 expect(testApi.calls.session).toBe(2);
294 });
295
296 + it("rejects a blank pairing token with a structured validation error", async () => {
297 + const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
298 + await import("./environments/primary/auth");
299 +
300 + const error = await submitServerAuthCredential(" ").then(
301 + () => null,
302 + (failure: unknown) => failure,
303 + );
304 +
305 + expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
306 + expect(error).toMatchObject({
307 + _tag: "PrimaryEnvironmentPairingCredentialRequiredError",
308 + providedLength: 3,
309 + message: "Enter a pairing token to continue.",
310 + });
311 + });
312 +
313 it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
314 const cause = new EnvironmentAuthInvalidError({
315 code: "auth_invalid",
@@ -299,7 +320,7 @@ describe("resolveInitialServerAuthGateState", () => {
320 browserSession: () => Effect.fail(cause),
321 });
322
302 - const { isPrimaryEnvironmentRequestError, submitServerAuthCredential } =
323 + const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
324 await import("./environments/primary");
325
326 const error = await submitServerAuthCredential("bad-token").then(
@@ -307,14 +328,13 @@ describe("resolveInitialServerAuthGateState", () => {
328 (failure: unknown) => failure,
329 );
330 expect(error).toMatchObject({
310 - _tag: "PrimaryEnvironmentRequestError",
311 - operation: "exchange-bootstrap-credential",
312 - status: 401,
313 - detail: "Invalid pairing token. Check the token and try again.",
331 + _tag: "PrimaryEnvironmentPairingCredentialRejectedError",
332 + providedLength: 9,
333 + message: "Invalid pairing token. Check the token and try again.",
334 });
315 - expect(isPrimaryEnvironmentRequestError(error)).toBe(true);
316 - if (!isPrimaryEnvironmentRequestError(error)) {
317 - throw new Error("Expected a structured primary environment request error.");
335 + expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
336 + if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
337 + throw new Error("Expected a structured rejected pairing credential error.");
338 }
339 expect(error.cause).toMatchObject({
340 _tag: "EnvironmentAuthInvalidError",
@@ -325,6 +345,22 @@ describe("resolveInitialServerAuthGateState", () => {
345 expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
346 });
347
348 + it("derives primary request messages from structural request context", async () => {
349 + const cause = new Error("private transport detail");
350 + const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
351 + const error = PrimaryEnvironmentRequestError.fromCause({
352 + operation: "list-pairing-links",
353 + cause,
354 + });
355 +
356 + expect(error.status).toBe(500);
357 + expect(error.cause).toBe(cause);
358 + expect(error.message).toBe(
359 + "Primary environment request failed during list-pairing-links (HTTP 500).",
360 + );
361 + expect(error.message).not.toContain(cause.message);
362 + });
363 +
364 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
365 vi.useFakeTimers();
366 const nextSession = sequence(
@@ -337,15 +373,7 @@ describe("resolveInitialServerAuthGateState", () => {
373 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
374 });
375
340 - const testWindow = installTestBrowser("http://localhost/");
341 - testWindow.desktopBridge = {
342 - getLocalEnvironmentBootstrap: () => ({
343 - label: "Local environment",
344 - httpBaseUrl: "http://localhost:3773",
345 - wsBaseUrl: "ws://localhost:3773",
346 - bootstrapToken: "desktop-bootstrap-token",
347 - }),
348 - } as DesktopBridge;
376 + installDesktopBootstrap();
377
378 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
379
@@ -356,6 +384,28 @@ describe("resolveInitialServerAuthGateState", () => {
384 expect(testApi.calls.session).toBe(3);
385 });
386
387 + it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
388 + vi.useFakeTimers();
389 + const testApi = await installAuthApi({
390 + session: () => unauthenticatedSession(DESKTOP_AUTH),
391 + browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
392 + });
393 +
394 + installDesktopBootstrap();
395 +
396 + const { resolveInitialServerAuthGateState } = await import("./environments/primary");
397 +
398 + const gateStatePromise = resolveInitialServerAuthGateState();
399 + await vi.advanceTimersByTimeAsync(2_000);
400 +
401 + await expect(gateStatePromise).resolves.toEqual({
402 + status: "requires-auth",
403 + auth: DESKTOP_AUTH,
404 + errorMessage: "Timed out waiting for authenticated session after bootstrap.",
405 + });
406 + expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
407 + });
408 +
409 it("memoizes the authenticated gate state after the first successful read", async () => {
410 const testApi = await installAuthApi({
411 session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
apps/web/src/environments/primary/auth.ts
+68 -54
@@ -40,7 +40,6 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
40 {
41 operation: PrimaryEnvironmentRequestOperation,
42 status: Schema.Number,
43 - detail: Schema.String,
43 pairingLinkId: Schema.optional(Schema.String),
44 sessionId: Schema.optional(Schema.String),
45 cause: Schema.Defect(),
@@ -49,17 +48,13 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
48 static fromCause(input: {
49 readonly operation: PrimaryEnvironmentRequestOperation;
50 readonly cause: unknown;
52 - readonly fallbackMessage: (status: number) => string;
53 - readonly formatDetail?: (detail: string, status: number) => string;
51 readonly pairingLinkId?: string;
52 readonly sessionId?: string;
53 }): PrimaryEnvironmentRequestError {
54 const status = readHttpApiStatus(input.cause) ?? 500;
58 - const rawDetail = readHttpApiErrorMessage(input.cause, input.fallbackMessage(status));
55 return new PrimaryEnvironmentRequestError({
56 operation: input.operation,
57 status,
62 - detail: input.formatDetail?.(rawDetail, status) ?? rawDetail,
58 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
59 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
60 cause: input.cause,
@@ -67,11 +62,59 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
62 }
63
64 override get message(): string {
70 - return this.detail;
65 + return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
66 }
67 }
68
69 export const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
70 +
71 +export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRejectedError>()(
72 + "PrimaryEnvironmentPairingCredentialRejectedError",
73 + {
74 + providedLength: Schema.Number,
75 + cause: Schema.Defect(),
76 + },
77 +) {
78 + override get message(): string {
79 + return "Invalid pairing token. Check the token and try again.";
80 + }
81 +}
82 +
83 +export const isPrimaryEnvironmentPairingCredentialRejectedError = Schema.is(
84 + PrimaryEnvironmentPairingCredentialRejectedError,
85 +);
86 +
87 +export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedErrorClass<PrimaryEnvironmentAuthSessionTimeoutError>()(
88 + "PrimaryEnvironmentAuthSessionTimeoutError",
89 + {
90 + timeoutMs: Schema.Number,
91 + elapsedMs: Schema.Number,
92 + },
93 +) {
94 + override get message(): string {
95 + return "Timed out waiting for authenticated session after bootstrap.";
96 + }
97 +}
98 +
99 +export const isPrimaryEnvironmentAuthSessionTimeoutError = Schema.is(
100 + PrimaryEnvironmentAuthSessionTimeoutError,
101 +);
102 +
103 +export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRequiredError>()(
104 + "PrimaryEnvironmentPairingCredentialRequiredError",
105 + {
106 + providedLength: Schema.Number,
107 + },
108 +) {
109 + override get message(): string {
110 + return "Enter a pairing token to continue.";
111 + }
112 +}
113 +
114 +export const isPrimaryEnvironmentPairingCredentialRequiredError = Schema.is(
115 + PrimaryEnvironmentPairingCredentialRequiredError,
116 +);
117 +
118 const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
119
120 export interface ServerPairingLinkRecord {
@@ -151,7 +194,6 @@ export async function fetchSessionState(): Promise<AuthSessionState> {
194 throw PrimaryEnvironmentRequestError.fromCause({
195 operation: "fetch-session-state",
196 cause: error,
154 - fallbackMessage: (status) => `Failed to load server auth session state (${status}).`,
197 });
198 }
199 });
@@ -180,42 +222,6 @@ function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType):
222 }
223 }
224
183 -function readHttpApiErrorMessage(error: unknown, fallbackMessage: string): string {
184 - if (!isEnvironmentHttpCommonError(error)) {
185 - return fallbackMessage;
186 - }
187 - switch (error._tag) {
188 - case "EnvironmentAuthInvalidError":
189 - return error.reason === "missing_credential"
190 - ? "Authentication required."
191 - : "Invalid bootstrap credential.";
192 - case "EnvironmentRequestInvalidError":
193 - return error.reason === "invalid_scope"
194 - ? "Requested token scope is invalid."
195 - : "Requested scope exceeds the bootstrap credential grant.";
196 - case "EnvironmentScopeRequiredError":
197 - return `The authenticated token is missing required scope: ${error.requiredScope}.`;
198 - case "EnvironmentOperationForbiddenError":
199 - return "This operation is not allowed for the current session.";
200 - case "EnvironmentInternalError":
201 - return fallbackMessage;
202 - }
203 -}
204 -
205 -const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([
206 - "Invalid bootstrap credential.",
207 - "Unknown bootstrap credential.",
208 -]);
209 -
210 -function toFriendlyBootstrapErrorMessage(status: number, message: string): string {
211 - const trimmedMessage = message.trim();
212 - if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(trimmedMessage)) {
213 - return "Invalid pairing token. Check the token and try again.";
214 - }
215 -
216 - return trimmedMessage;
217 -}
218 -
225 async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
226 return retryTransientBootstrap(async () => {
227 try {
@@ -225,11 +231,19 @@ async function exchangeBootstrapCredential(credential: string): Promise<AuthBrow
231 ),
232 );
233 } catch (error) {
234 + if (
235 + isEnvironmentHttpCommonError(error) &&
236 + error._tag === "EnvironmentAuthInvalidError" &&
237 + error.reason === "invalid_credential"
238 + ) {
239 + throw new PrimaryEnvironmentPairingCredentialRejectedError({
240 + providedLength: credential.length,
241 + cause: error,
242 + });
243 + }
244 throw PrimaryEnvironmentRequestError.fromCause({
245 operation: "exchange-bootstrap-credential",
246 cause: error,
231 - fallbackMessage: (status) => `Failed to bootstrap auth session (${status}).`,
232 - formatDetail: (detail, status) => toFriendlyBootstrapErrorMessage(status, detail),
247 });
248 }
249 });
@@ -244,8 +258,12 @@ async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionS
258 return session;
259 }
260
247 - if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
248 - throw new Error("Timed out waiting for authenticated session after bootstrap.");
261 + const elapsedMs = Date.now() - startedAt;
262 + if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
263 + throw new PrimaryEnvironmentAuthSessionTimeoutError({
264 + timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
265 + elapsedMs,
266 + });
267 }
268
269 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
@@ -323,7 +341,9 @@ async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
341 export async function submitServerAuthCredential(credential: string): Promise<void> {
342 const trimmedCredential = credential.trim();
343 if (!trimmedCredential) {
326 - throw new Error("Enter a pairing token to continue.");
344 + throw new PrimaryEnvironmentPairingCredentialRequiredError({
345 + providedLength: credential.length,
346 + });
347 }
348
349 resolvedAuthenticatedGateState = null;
@@ -355,7 +375,6 @@ export async function createServerPairingCredential(input?: {
375 throw PrimaryEnvironmentRequestError.fromCause({
376 operation: "create-pairing-credential",
377 cause: error,
358 - fallbackMessage: (status) => `Failed to create pairing credential (${status}).`,
378 });
379 }
380 }
@@ -396,7 +415,6 @@ export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPair
415 throw PrimaryEnvironmentRequestError.fromCause({
416 operation: "list-pairing-links",
417 cause: error,
399 - fallbackMessage: (status) => `Failed to load pairing links (${status}).`,
418 });
419 }
420 }
@@ -413,7 +431,6 @@ export async function revokeServerPairingLink(id: string): Promise<void> {
431 operation: "revoke-pairing-link",
432 pairingLinkId: id,
433 cause: error,
416 - fallbackMessage: (status) => `Failed to revoke pairing link (${status}).`,
434 });
435 }
436 }
@@ -446,7 +463,6 @@ export async function listServerClientSessions(): Promise<
463 throw PrimaryEnvironmentRequestError.fromCause({
464 operation: "list-client-sessions",
465 cause: error,
449 - fallbackMessage: (status) => `Failed to load paired clients (${status}).`,
466 });
467 }
468 }
@@ -465,7 +481,6 @@ export async function revokeServerClientSession(sessionId: AuthSessionId): Promi
481 operation: "revoke-client-session",
482 sessionId,
483 cause: error,
468 - fallbackMessage: (status) => `Failed to revoke client session (${status}).`,
484 });
485 }
486 }
@@ -482,7 +497,6 @@ export async function revokeOtherServerClientSessions(): Promise<number> {
497 throw PrimaryEnvironmentRequestError.fromCause({
498 operation: "revoke-other-client-sessions",
499 cause: error,
485 - fallbackMessage: (status) => `Failed to revoke other client sessions (${status}).`,
500 });
501 }
502 }
apps/web/src/environments/primary/context.ts
-1
@@ -46,7 +46,6 @@ async function fetchPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironment
46 throw PrimaryEnvironmentRequestError.fromCause({
47 operation: "fetch-environment-descriptor",
48 cause: error,
49 - fallbackMessage: (status) => `Failed to load server environment descriptor (${status}).`,
49 });
50 }
51
apps/web/src/environments/primary/index.ts
+2
@@ -16,10 +16,12 @@ export {
16 export {
17 createServerPairingCredential,
18 fetchSessionState,
19 + isPrimaryEnvironmentPairingCredentialRejectedError,
20 isPrimaryEnvironmentRequestError,
21 listServerClientSessions,
22 listServerPairingLinks,
23 peekPairingTokenFromUrl,
24 + PrimaryEnvironmentPairingCredentialRejectedError,
25 PrimaryEnvironmentRequestError,
26 resolveInitialServerAuthGateState,
27 revokeOtherServerClientSessions,