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

main
ts 139 lines 4.87 KB
Raw
1 import {
2 type DpopVerificationFailureCode as DpopVerificationFailureCodeType,
3 verifyDpopProof,
4 } from "@t3tools/shared/dpop";
5 import type { DpopFailureReason } from "@t3tools/contracts";
6 import * as Digest from "effect/crypto/Digest";
7 import * as DateTime from "effect/DateTime";
8 import * as Effect from "effect/Effect";
9 import * as Base64Url from "effect/encoding/Base64Url";
10 import * as Option from "effect/Option";
11 import * as HttpServerRequest from "effect/http/HttpServerRequest";
12
13 import {
14 ServerAuthDpopReplayKeyCalculationError,
15 ServerAuthDpopReplayStateRecordError,
16 ServerAuthInvalidCredentialError,
17 type ServerAuthInternalError,
18 } from "./EnvironmentAuth.ts";
19 import * as ServerSecretStore from "./ServerSecretStore.ts";
20 import { requestUrl } from "../requestUrl.ts";
21
22 export const DPOP_REPLAY_MARKER_PREFIX = "dpop-proof-";
23
24 const mapDpopFailureReason = (code: DpopVerificationFailureCodeType): DpopFailureReason => {
25 switch (code) {
26 case "time_window":
27 return "time_window";
28 case "key_mismatch":
29 return "key_mismatch";
30 case "method_mismatch":
31 case "url_mismatch":
32 return "request_mismatch";
33 case "access_token_hash_mismatch":
34 return "token_mismatch";
35 case "missing_proof":
36 case "malformed_proof":
37 case "invalid_signature":
38 case "invalid_proof":
39 return "invalid_proof";
40 }
41 };
42
43 export const mapDpopReplayStoreError = (
44 error: ServerSecretStore.SecretStoreError,
45 ): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
46 ServerSecretStore.isSecretAlreadyExistsError(error)
47 ? new ServerAuthInvalidCredentialError({
48 diagnostic: "DPoP proof replayed.",
49 dpopFailureReason: "replay",
50 cause: error,
51 })
52 : new ServerAuthDpopReplayStateRecordError({
53 cause: error,
54 });
55
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;
61 readonly expectedThumbprint?: string;
62 readonly expectedAccessToken?: string;
63 }) {
64 const proof = input.proof ?? input.request.headers.dpop;
65 const url = requestUrl(input.request);
66 if (Option.isNone(url)) {
67 return yield* new ServerAuthInvalidCredentialError({
68 diagnostic: "Invalid DPoP request URL.",
69 });
70 }
71 const now = yield* DateTime.now;
72 const result = verifyDpopProof({
73 proof,
74 method: input.request.method,
75 url: url.value.href,
76 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
77 ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
78 ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
79 });
80 if (!result.ok) {
81 yield* Effect.annotateCurrentSpan({
82 "environment.dpop.failure_code": result.code,
83 });
84 return yield* new ServerAuthInvalidCredentialError({
85 diagnostic: result.reason,
86 dpopFailureReason: mapDpopFailureReason(result.code),
87 });
88 }
89 const secretStore = yield* ServerSecretStore.ServerSecretStore;
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 });