Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

dpop.ts

125 lines4.2 KB

1import {
2 type DpopVerificationFailureCode as DpopVerificationFailureCodeType,
3 verifyDpopProof,
4} from "@t3tools/shared/dpop";
5import type { DpopFailureReason } from "@t3tools/contracts";
6import * as Crypto from "effect/Crypto";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Base64Url from "effect/encoding/Base64Url";
10import * as Option from "effect/Option";
11import * as HttpServerRequest from "effect/http/HttpServerRequest";
12​
13import {
14 ServerAuthDpopReplayKeyCalculationError,
15 ServerAuthDpopReplayStateRecordError,
16 ServerAuthInvalidCredentialError,
17 type ServerAuthInternalError,
18} from "./EnvironmentAuth.ts";
19import * as ServerSecretStore from "./ServerSecretStore.ts";
20​
21export const DPOP_REPLAY_MARKER_PREFIX = "dpop-proof-";
22​
23export const mapDpopFailureReason = (code: DpopVerificationFailureCodeType): DpopFailureReason => {
24 switch (code) {
25 case "time_window":
26 return "time_window";
27 case "key_mismatch":
28 return "key_mismatch";
29 case "method_mismatch":
30 case "url_mismatch":
31 return "request_mismatch";
32 case "access_token_hash_mismatch":
33 return "token_mismatch";
34 case "missing_proof":
35 case "malformed_proof":
36 case "invalid_signature":
37 case "invalid_proof":
38 return "invalid_proof";
39 }
40};
41​
42export const mapDpopReplayStoreError = (
43 error: ServerSecretStore.SecretStoreError,
44): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
45 ServerSecretStore.isSecretAlreadyExistsError(error)
46 ? new ServerAuthInvalidCredentialError({
47 diagnostic: "DPoP proof replayed.",
48 dpopFailureReason: "replay",
49 cause: error,
50 })
51 : new ServerAuthDpopReplayStateRecordError({
52 cause: error,
53 });
54​
55export const verifyRequestDpopProof = (input: {
56 readonly request: HttpServerRequest.HttpServerRequest;
57 readonly expectedThumbprint?: string;
58 readonly expectedAccessToken?: string;
59}) =>
60 Effect.gen(function* () {
61 const proof = input.request.headers.dpop;
62 const url = HttpServerRequest.toURL(input.request);
63 if (Option.isNone(url)) {
64 return yield* new ServerAuthInvalidCredentialError({
65 diagnostic: "Invalid DPoP request URL.",
66 });
67 }
68 const now = yield* DateTime.now;
69 const result = verifyDpopProof({
70 proof,
71 method: input.request.method,
72 url: url.value.href,
73 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
74 ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
75 ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
76 });
77 if (!result.ok) {
78 yield* Effect.annotateCurrentSpan({
79 "environment.dpop.failure_code": result.code,
80 });
81 return yield* new ServerAuthInvalidCredentialError({
82 diagnostic: result.reason,
83 dpopFailureReason: mapDpopFailureReason(result.code),
84 });
85 }
86 const secretStore = yield* ServerSecretStore.ServerSecretStore;
87 const replayKey = yield* Crypto.Crypto.pipe(
88 Effect.flatMap((crypto) =>
89 crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
90 ),
91 Effect.map(Base64Url.encode),
92 Effect.mapError(
93 (cause) =>
94 new ServerAuthDpopReplayKeyCalculationError({
95 cause,
96 }),
97 ),
98 );
99 yield* secretStore
100 .create(
101 `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
102 new TextEncoder().encode(
103 [
104 `thumbprint=${result.thumbprint}`,
105 `jti=${result.jti}`,
106 `iat=${result.iat}`,
107 `consumedAt=${DateTime.formatIso(now)}`,
108 ].join("\n"),
109 ),
110 )
111 .pipe(
112 Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
113 Effect.gen(function* () {
114 const mapped = mapDpopReplayStoreError(error);
115 if (mapped._tag === "ServerAuthInvalidCredentialError") {
116 yield* Effect.annotateCurrentSpan({
117 "environment.dpop.failure_code": mapped.dpopFailureReason,
118 });
119 }
120 return yield* mapped;
121 }),
122 ),
123 );
124 return result.thumbprint;
125 });