Open History to see the last commit
1import { verifyDpopProof } from "@t3tools/shared/dpop";
2import * as Crypto from "effect/Crypto";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Encoding from "effect/Encoding";
6import * as Option from "effect/Option";
7import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
8
9import {
10 ServerAuthDpopReplayKeyCalculationError,
11 ServerAuthDpopReplayStateRecordError,
12 ServerAuthInvalidCredentialError,
13 type ServerAuthInternalError,
14} from "./EnvironmentAuth.ts";
15import * as ServerSecretStore from "./ServerSecretStore.ts";
16
17export const mapDpopReplayStoreError = (
18 error: ServerSecretStore.SecretStoreError,
19): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
20 ServerSecretStore.isSecretAlreadyExistsError(error)
21 ? new ServerAuthInvalidCredentialError({
22 diagnostic: "DPoP proof replayed.",
23 cause: error,
24 })
25 : new ServerAuthDpopReplayStateRecordError({
26 cause: error,
27 });
28
29export const verifyRequestDpopProof = (input: {
30 readonly request: HttpServerRequest.HttpServerRequest;
31 readonly expectedThumbprint?: string;
32 readonly expectedAccessToken?: string;
33}) =>
34 Effect.gen(function* () {
35 const proof = input.request.headers.dpop;
36 const url = HttpServerRequest.toURL(input.request);
37 if (Option.isNone(url)) {
38 return yield* new ServerAuthInvalidCredentialError({
39 diagnostic: "Invalid DPoP request URL.",
40 });
41 }
42 const now = yield* DateTime.now;
43 const result = verifyDpopProof({
44 proof,
45 method: input.request.method,
46 url: url.value.href,
47 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
48 ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
49 ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
50 });
51 if (!result.ok) {
52 return yield* new ServerAuthInvalidCredentialError({
53 diagnostic: result.reason,
54 });
55 }
56 const secretStore = yield* ServerSecretStore.ServerSecretStore;
57 const replayKey = yield* Crypto.Crypto.pipe(
58 Effect.flatMap((crypto) =>
59 crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),
60 ),
61 Effect.map(Encoding.encodeBase64Url),
62 Effect.mapError(
63 (cause) =>
64 new ServerAuthDpopReplayKeyCalculationError({
65 cause,
66 }),
67 ),
68 );
69 yield* secretStore
70 .create(
71 `dpop-proof-${replayKey}`,
72 new TextEncoder().encode(
73 [
74 `thumbprint=${result.thumbprint}`,
75 `jti=${result.jti}`,
76 `iat=${result.iat}`,
77 `consumedAt=${DateTime.formatIso(now)}`,
78 ].join("\n"),
79 ),
80 )
81 .pipe(
82 Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
83 Effect.fail(mapDpopReplayStoreError(error)),
84 ),
85 );
86 return result.thumbprint;
87 });