The best way to control Claude Code, Codex and more from any computer or phone
fix: hosted agent approval no longer fails with "Your session cannot approve" (#33645)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 9, 2026 at 17:42 UTC
eb381a7d4f4475d60fbb1f59efe9f204de59bba8
5 files changed
+114
-51
apps/server/src/auth/EnvironmentAuth.test.ts
+1
-38
@@ -1,14 +1,6 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2
-import * as NodeCrypto from "node:crypto";
3
-
1
import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import { authScopeResponse, AuthStandardClientScopes } from "@t3tools/contracts";
7
-import {
8
- computeDpopAccessTokenHash,
9
- computeDpopJwkThumbprint,
10
- type DpopPublicJwk,
11
-} from "@t3tools/shared/dpop";
4
import { expect, it } from "@effect/vitest";
5
import * as DateTime from "effect/DateTime";
6
import * as Effect from "effect/Effect";
@@ -16,6 +8,7 @@ import * as Layer from "effect/Layer";
8
import * as Redacted from "effect/Redacted";
9
10
import * as ServerConfig from "../config.ts";
11
+import { makeDpopKey } from "./dpop.testkit.ts";
12
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
13
import * as SqlitePersistence from "../persistence/Sqlite.ts";
14
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
@@ -80,36 +73,6 @@ const requestMetadata = {
73
ipAddress: "192.168.1.23",
74
};
75
83
-const makeDpopKey = () => {
84
- const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
85
- const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;
86
- let proofCount = 0;
87
- return {
88
- thumbprint: computeDpopJwkThumbprint(publicJwk),
89
- sign: (input: {
90
- readonly method: string;
91
- readonly url: string;
92
- readonly token: string;
93
- readonly iat: number;
94
- }) => {
95
- const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
96
- const header = encode({ typ: "dpop+jwt", alg: "ES256", jwk: publicJwk });
97
- const payload = encode({
98
- htm: input.method,
99
- htu: input.url,
100
- jti: `proof-${++proofCount}`,
101
- iat: input.iat,
102
- ath: computeDpopAccessTokenHash(input.token),
103
- });
104
- const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {
105
- key: privateKey,
106
- dsaEncoding: "ieee-p1363",
107
- }).toString("base64url");
108
- return `${header}.${payload}.${signature}`;
109
- },
110
- };
111
-};
112
-
76
it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
77
"EnvironmentAuth.layer",
78
(it) => {
apps/server/src/auth/McpOAuth.test.ts
+54
-6
@@ -10,6 +10,7 @@ import {
10
mcpClientScopes,
11
} from "@t3tools/contracts";
12
import { expect, it } from "@effect/vitest";
13
+import * as Clock from "effect/Clock";
14
import * as Context from "effect/Context";
15
import * as SecureRandom from "effect/crypto/SecureRandom";
16
import * as Effect from "effect/Effect";
@@ -24,6 +25,7 @@ import * as Schema from "effect/Schema";
25
26
import * as CloudLink from "../cloud/CloudLink.ts";
27
import * as ServerConfig from "../config.ts";
28
+import { makeDpopKey } from "./dpop.testkit.ts";
29
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30
import * as ServerSettings from "../serverSettings.ts";
31
import * as Sqlite from "../persistence/Sqlite.ts";
@@ -130,17 +132,19 @@ const withRoutes = <A, E>(
132
133
const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
134
133
-/** `credential` is a browser cookie, or `Bearer <token>` for a session such as T3 Connect's. */
134
-const postJson = (path: string, body: unknown, credential?: string) =>
135
+/** `credential` is a browser cookie, `Bearer <token>`, or the headers of a DPoP request. */
136
+const postJson = (path: string, body: unknown, credential?: string | Record<string, string>) =>
137
at(path, {
138
method: "POST",
139
headers: {
140
"content-type": "application/json",
141
...(credential === undefined
142
? {}
141
- : credential.startsWith("Bearer ")
142
- ? { authorization: credential }
143
- : { cookie: credential }),
143
+ : typeof credential !== "string"
144
+ ? credential
145
+ : credential.startsWith("Bearer ")
146
+ ? { authorization: credential }
147
+ : { cookie: credential }),
148
},
149
body: encodeJson(body),
150
});
@@ -149,7 +153,7 @@ const decide = (
153
handler: Handler,
154
authorization: Record<string, string>,
155
decision: Record<string, string>,
152
- cookie?: string,
156
+ cookie?: string | Record<string, string>,
157
) =>
158
handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe(
159
Effect.flatMap((response) =>
@@ -742,6 +746,50 @@ it.live("one-click approves only access the browser session holds the scopes for
746
connect,
747
);
748
expect(new URL(viaConnect.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
749
+
750
+ // The hosted app may load and decide with two credentials minted for the same browser key.
751
+ const key = makeDpopKey();
752
+ const dpopSession = (thumbprint: string) =>
753
+ auth.issuePairingCredential({ scopes: [...AuthStandardClientScopes] }).pipe(
754
+ Effect.flatMap((pairing) =>
755
+ auth.exchangeBootstrapCredentialForAccessToken(
756
+ pairing.credential,
757
+ undefined,
758
+ { deviceType: "desktop" },
759
+ { proofKeyThumbprint: thumbprint },
760
+ ),
761
+ ),
762
+ Effect.map((exchanged) => exchanged.access_token),
763
+ );
764
+ const iat = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
765
+ const dpopHeaders = (signer: typeof key, token: string, path: string) => ({
766
+ authorization: `DPoP ${token}`,
767
+ dpop: signer.sign({ method: "POST", url: `${ORIGIN}${path}`, token, iat }),
768
+ });
769
+ const loadedWith = yield* dpopSession(key.thumbprint);
770
+ const loaded = yield* handler(
771
+ postJson(
772
+ "/oauth/mcp/approval",
773
+ params,
774
+ dpopHeaders(key, loadedWith, "/oauth/mcp/approval"),
775
+ ),
776
+ ).pipe(Effect.flatMap(json<{ csrfToken?: string }>));
777
+ const renewed = yield* dpopSession(key.thumbprint);
778
+ const sameKey = yield* decide(
779
+ handler,
780
+ params,
781
+ { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! },
782
+ dpopHeaders(key, renewed, "/oauth/mcp/decision"),
783
+ );
784
+ expect(new URL(sameKey.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
785
+ const otherKey = makeDpopKey();
786
+ const elsewhere = yield* decide(
787
+ handler,
788
+ params,
789
+ { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! },
790
+ dpopHeaders(otherKey, yield* dpopSession(otherKey.thumbprint), "/oauth/mcp/decision"),
791
+ );
792
+ expect(elsewhere.status).toBe(400);
793
}),
794
),
795
);
apps/server/src/auth/McpOAuth.ts
+9
-5
@@ -307,11 +307,11 @@ const make = Effect.gen(function* () {
307
)
308
: Effect.succeed(false);
309
310
- const csrfToken = (sessionId: string, authorization: AuthorizationRequest) =>
310
+ const csrfToken = (holder: string, authorization: AuthorizationRequest) =>
311
sign(
312
"mcp-csrf",
313
JSON.stringify([
314
- sessionId,
314
+ holder,
315
authorization.client.clientId,
316
authorization.redirectUri,
317
authorization.codeChallenge,
@@ -413,9 +413,13 @@ const make = Effect.gen(function* () {
413
// Approving manages access, and a session may only hand out scopes it holds.
414
session.scopes.includes(AuthAccessWriteScope) &&
415
session.scopes.includes(AuthOrchestrationReadScope)
416
- ? csrfToken(session.sessionId, authorization).pipe(
417
- Effect.map((token) => ({ csrfToken: token, scopes: session.scopes })),
418
- )
416
+ ? // The hosted app may get a fresh credential per call, all bound to one browser key.
417
+ csrfToken(
418
+ session.proofKeyThumbprint === undefined
419
+ ? session.sessionId
420
+ : `dpop:${session.proofKeyThumbprint}`,
421
+ authorization,
422
+ ).pipe(Effect.map((token) => ({ csrfToken: token, scopes: session.scopes })))
423
: Effect.undefined,
424
),
425
Effect.orElseSucceed(() => undefined),
apps/server/src/auth/dpop.testkit.ts
new
+39
@@ -0,0 +1,39 @@
1
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2
+import * as NodeCrypto from "node:crypto";
3
+
4
+import {
5
+ computeDpopAccessTokenHash,
6
+ computeDpopJwkThumbprint,
7
+ type DpopPublicJwk,
8
+} from "@t3tools/shared/dpop";
9
+
10
+/** A client's DPoP key, signing proofs the way a browser or the mobile app does. */
11
+export const makeDpopKey = () => {
12
+ const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" });
13
+ const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;
14
+ let proofCount = 0;
15
+ return {
16
+ thumbprint: computeDpopJwkThumbprint(publicJwk),
17
+ sign: (input: {
18
+ readonly method: string;
19
+ readonly url: string;
20
+ readonly token: string;
21
+ readonly iat: number;
22
+ }) => {
23
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
24
+ const header = encode({ typ: "dpop+jwt", alg: "ES256", jwk: publicJwk });
25
+ const payload = encode({
26
+ htm: input.method,
27
+ htu: input.url,
28
+ jti: `proof-${++proofCount}`,
29
+ iat: input.iat,
30
+ ath: computeDpopAccessTokenHash(input.token),
31
+ });
32
+ const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {
33
+ key: privateKey,
34
+ dsaEncoding: "ieee-p1363",
35
+ }).toString("base64url");
36
+ return `${header}.${payload}.${signature}`;
37
+ },
38
+ };
39
+};
packages/client-runtime/src/state/connectMcpApproval.ts
+11
-2
@@ -9,6 +9,7 @@ import type {
9
EnvironmentId,
10
} from "@t3tools/contracts";
11
import * as Effect from "effect/Effect";
12
+import * as Option from "effect/Option";
13
import type * as HttpClient from "effect/http/HttpClient";
14
import type { Atom } from "effect/reactivity";
15
import * as Schema from "effect/Schema";
@@ -75,8 +76,16 @@ const callConnectMcpApproval = Effect.fn("clientRuntime.state.connectMcpApproval
76
}),
77
},
78
signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
78
- remoteAuthorization: yield* Effect.serviceOption(
79
- RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
79
+ // A token for an unsaved environment is not cached, so reuse this one until it is rejected.
80
+ remoteAuthorization: Option.some(
81
+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
82
+ ...remote,
83
+ // Untraced: the relay authorization it may call owns the span.
84
+ authorizeDpopHttp: Effect.fnUntraced(function* (request) {
85
+ if (request.rejectedAccessToken === undefined) return authorized;
86
+ return yield* remote.authorizeDpopHttp(request);
87
+ }),
88
+ }),
89
),
90
group: "mcpOAuth",
91
method: "POST",