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

dpop.ts

124 lines4.0 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 = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: {
56 readonly request: HttpServerRequest.HttpServerRequest;
57 readonly expectedThumbprint?: string;
58 readonly expectedAccessToken?: string;
59}) {
60 const proof = input.request.headers.dpop;
61 const url = HttpServerRequest.toURL(input.request);
62 if (Option.isNone(url)) {
63 return yield* new ServerAuthInvalidCredentialError({
64 diagnostic: "Invalid DPoP request URL.",
65 });
66 }
67 const now = yield* DateTime.now;
68 const result = verifyDpopProof({
69 proof,
70 method: input.request.method,
71 url: url.value.href,
72 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
73 ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
74 ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
75 });
76 if (!result.ok) {
77 yield* Effect.annotateCurrentSpan({
78 "environment.dpop.failure_code": result.code,
79 });
80 return yield* new ServerAuthInvalidCredentialError({
81 diagnostic: result.reason,
82 dpopFailureReason: mapDpopFailureReason(result.code),
83 });
84 }
85 const secretStore = yield* ServerSecretStore.ServerSecretStore;
86 const replayKey = yield* Crypto.Crypto.pipe(
87 Effect.flatMap((crypto) =>
88 crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
89 ),
90 Effect.map(Base64Url.encode),
91 Effect.mapError(
92 (cause) =>
93 new ServerAuthDpopReplayKeyCalculationError({
94 cause,
95 }),
96 ),
97 );
98 yield* secretStore
99 .create(
100 `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
101 new TextEncoder().encode(
102 [
103 `thumbprint=${result.thumbprint}`,
104 `jti=${result.jti}`,
105 `iat=${result.iat}`,
106 `consumedAt=${DateTime.formatIso(now)}`,
107 ].join("\n"),
108 ),
109 )
110 .pipe(
111 Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
112 Effect.gen(function* () {
113 const mapped = mapDpopReplayStoreError(error);
114 if (mapped._tag === "ServerAuthInvalidCredentialError") {
115 yield* Effect.annotateCurrentSpan({
116 "environment.dpop.failure_code": mapped.dpopFailureReason,
117 });
118 }
119 return yield* mapped;
120 }),
121 ),
122 );
123 return result.thumbprint;
124});