The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 16:00 UTC
fix(server): unauthenticated token requests no longer write DPoP replay markers (#36393)
Julius Marminge committed
Nov 13, 2026 at 13:38 UTC
4ee3b602fc25368c8eea1fa88fceab180db9034b
3 files changed
+119
-43
apps/server/src/auth/dpop.ts
+51
-39
@@ -53,7 +53,8 @@ export const mapDpopReplayStoreError = (
53
cause: error,
54
});
55
56
-export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {
56
+/** Checks a proof without recording it; `consume` records its jti so it cannot be replayed. */
57
+export const checkRequestDpopProof = Effect.fn("dpop.checkRequestDpopProof")(function* (input: {
58
readonly request: HttpServerRequest.HttpServerRequest;
59
/** Overrides the `DPoP` header for requests that cannot carry one, such as a WebSocket upgrade. */
60
readonly proof?: string;
@@ -86,42 +87,53 @@ export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(f
87
});
88
}
89
const secretStore = yield* ServerSecretStore.ServerSecretStore;
89
- const replayKey = yield* Digest.Digest.pipe(
90
- Effect.flatMap((digest) =>
91
- digest.digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
92
- ),
93
- Effect.map(Base64Url.encode),
94
- Effect.mapError(
95
- (cause) =>
96
- new ServerAuthDpopReplayKeyCalculationError({
97
- cause,
98
- }),
99
- ),
100
- );
101
- yield* secretStore
102
- .create(
103
- `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
104
- new TextEncoder().encode(
105
- [
106
- `thumbprint=${result.thumbprint}`,
107
- `jti=${result.jti}`,
108
- `iat=${result.iat}`,
109
- `consumedAt=${DateTime.formatIso(now)}`,
110
- ].join("\n"),
111
- ),
112
- )
113
- .pipe(
114
- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
115
- Effect.gen(function* () {
116
- const mapped = mapDpopReplayStoreError(error);
117
- if (mapped._tag === "ServerAuthInvalidCredentialError") {
118
- yield* Effect.annotateCurrentSpan({
119
- "environment.dpop.failure_code": mapped.dpopFailureReason,
120
- });
121
- }
122
- return yield* mapped;
123
- }),
124
- ),
125
- );
126
- return result.thumbprint;
90
+ const digest = yield* Digest.Digest;
91
+ const consume: Effect.Effect<void, ServerAuthInvalidCredentialError | ServerAuthInternalError> =
92
+ Effect.gen(function* () {
93
+ const replayKey = yield* digest
94
+ .digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`))
95
+ .pipe(
96
+ Effect.map(Base64Url.encode),
97
+ Effect.mapError(
98
+ (cause) =>
99
+ new ServerAuthDpopReplayKeyCalculationError({
100
+ cause,
101
+ }),
102
+ ),
103
+ );
104
+ yield* secretStore
105
+ .create(
106
+ `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
107
+ new TextEncoder().encode(
108
+ [
109
+ `thumbprint=${result.thumbprint}`,
110
+ `jti=${result.jti}`,
111
+ `iat=${result.iat}`,
112
+ `consumedAt=${DateTime.formatIso(now)}`,
113
+ ].join("\n"),
114
+ ),
115
+ )
116
+ .pipe(
117
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
118
+ Effect.gen(function* () {
119
+ const mapped = mapDpopReplayStoreError(error);
120
+ if (mapped._tag === "ServerAuthInvalidCredentialError") {
121
+ yield* Effect.annotateCurrentSpan({
122
+ "environment.dpop.failure_code": mapped.dpopFailureReason,
123
+ });
124
+ }
125
+ return yield* mapped;
126
+ }),
127
+ ),
128
+ );
129
+ });
130
+ return { thumbprint: result.thumbprint, consume };
131
+});
132
+
133
+export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (
134
+ input: Parameters<typeof checkRequestDpopProof>[0],
135
+) {
136
+ const proof = yield* checkRequestDpopProof(input);
137
+ yield* proof.consume;
138
+ return proof.thumbprint;
139
});
apps/server/src/auth/http.test.ts
+62
@@ -8,6 +8,7 @@ import {
8
} from "@t3tools/contracts";
9
import { expect, it } from "@effect/vitest";
10
import * as Context from "effect/Context";
11
+import * as DateTime from "effect/DateTime";
12
import * as SecureRandom from "effect/crypto/SecureRandom";
13
import * as Effect from "effect/Effect";
14
import * as Layer from "effect/Layer";
@@ -23,6 +24,7 @@ import * as ServerConfig from "../config.ts";
24
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
25
import * as SqlitePersistence from "../persistence/Sqlite.ts";
26
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
27
+import { makeDpopKey } from "./dpop.testkit.ts";
28
import * as ServerSecretStore from "./ServerSecretStore.ts";
29
import * as AuthHttp from "./http.ts";
30
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
@@ -191,3 +193,63 @@ it.effect.each(["DPoP", "dpop"])("challenges a refused %s request with DPoP", (s
193
);
194
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
195
);
196
+
197
+// The web handler runs on its own runtime, so proofs need wall-clock time.
198
+it.live("checks token-endpoint DPoP proofs without writing replay state", () =>
199
+ Effect.gen(function* () {
200
+ const random = yield* SecureRandom.SecureRandom;
201
+ const written: Array<string> = [];
202
+ const recordingSecretStore = ServerSecretStore.ServerSecretStore.of({
203
+ get: () => Effect.succeedNone,
204
+ set: () => Effect.void,
205
+ create: (name) => Effect.sync(() => void written.push(name)),
206
+ getOrCreateRandom: () => Effect.die("Not used by these routes."),
207
+ remove: () => Effect.void,
208
+ });
209
+ const requestContext = Context.make(SecureRandom.SecureRandom, random).pipe(
210
+ Context.add(ServerSecretStore.ServerSecretStore, recordingSecretStore),
211
+ );
212
+ const url = "http://127.0.0.1/oauth/token";
213
+ const key = makeDpopKey();
214
+ const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000);
215
+ const tokenRequest = (subjectToken: string, proof: string) =>
216
+ new Request(url, {
217
+ method: "POST",
218
+ headers: { host: "127.0.0.1", dpop: proof },
219
+ body: new URLSearchParams({
220
+ grant_type: AuthTokenExchangeGrantType,
221
+ subject_token: subjectToken,
222
+ subject_token_type: AuthEnvironmentBootstrapTokenType,
223
+ requested_token_type: AuthAccessTokenType,
224
+ }),
225
+ });
226
+ return yield* Effect.acquireUseRelease(
227
+ Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
228
+ (environment) =>
229
+ Effect.promise(async () => {
230
+ const unknownToken = await environment.handler(
231
+ tokenRequest("not-a-pairing-token", key.sign({ method: "POST", url, token: "", iat })),
232
+ requestContext,
233
+ );
234
+ expect(unknownToken.status).toBe(401);
235
+ expect(await unknownToken.json()).not.toHaveProperty("dpopFailureReason");
236
+
237
+ const accepted = await environment.handler(
238
+ tokenRequest(DEV_TOKEN, key.sign({ method: "POST", url, token: "", iat })),
239
+ requestContext,
240
+ );
241
+ expect(accepted.status).toBe(200);
242
+ expect(await accepted.json()).toMatchObject({ token_type: "DPoP" });
243
+
244
+ const badProof = await environment.handler(
245
+ tokenRequest(DEV_TOKEN, "not-a-proof"),
246
+ requestContext,
247
+ );
248
+ expect(badProof.status).toBe(401);
249
+ expect(badProof.headers.get("www-authenticate")).toBe("DPoP");
250
+ expect(written).toEqual([]);
251
+ }),
252
+ (environment) => Effect.promise(() => environment.dispose()),
253
+ );
254
+ }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
255
+);
apps/server/src/auth/http.ts
+6
-4
@@ -36,7 +36,7 @@ import * as EnvironmentAuth from "./EnvironmentAuth.ts";
36
import * as SessionStore from "./SessionStore.ts";
37
import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";
38
import { deriveAuthClientMetadata } from "./utils.ts";
39
-import { verifyRequestDpopProof } from "./dpop.ts";
39
+import { checkRequestDpopProof } from "./dpop.ts";
40
import { requestUrl } from "../requestUrl.ts";
41
42
const CREDENTIAL_RESPONSE_HEADERS = {
@@ -364,8 +364,10 @@ export const layer = HttpApiBuilder.group(
364
if (requestedScopes === null || requestedScopes?.length === 0) {
365
return yield* failEnvironmentInvalidRequest("invalid_scope");
366
}
367
- const proofKeyThumbprint = args.headers.dpop
368
- ? yield* verifyRequestDpopProof({ request }).pipe(
367
+ // Not recorded: a replayer also holds the subject token and could sign its own proof.
368
+ // Recording would let anyone write replay state to disk.
369
+ const proof = args.headers.dpop
370
+ ? yield* checkRequestDpopProof({ request }).pipe(
371
Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
372
appendDpopChallengeHeader.pipe(
373
Effect.andThen(
@@ -395,7 +397,7 @@ export const layer = HttpApiBuilder.group(
397
...(args.payload.client_os ? { os: args.payload.client_os } : {}),
398
},
399
}),
398
- proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
400
+ proof ? { proofKeyThumbprint: proof.thumbprint } : undefined,
401
);
402
},
403
traceRelayRequest,