Repository navigation
Expand file tree
/
Copy pathdpop.ts
More file actions
139 lines (133 loc) · 4.87 KB
/
Copy pathdpop.ts
File metadata and controls
139 lines (133 loc) · 4.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import {
type DpopVerificationFailureCode as DpopVerificationFailureCodeType,
verifyDpopProof,
} from "@t3tools/shared/dpop";
import type { DpopFailureReason } from "@t3tools/contracts";
import * as Digest from "effect/crypto/Digest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
ServerAuthDpopReplayStateRecordError,
ServerAuthInvalidCredentialError,
type ServerAuthInternalError,
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import { requestUrl } from "../requestUrl.ts";
export const DPOP_REPLAY_MARKER_PREFIX = "dpop-proof-";
const mapDpopFailureReason = (code: DpopVerificationFailureCodeType): DpopFailureReason => {
switch (code) {
case "time_window":
return "time_window";
case "key_mismatch":
return "key_mismatch";
case "method_mismatch":
case "url_mismatch":
return "request_mismatch";
case "access_token_hash_mismatch":
return "token_mismatch";
case "missing_proof":
case "malformed_proof":
case "invalid_signature":
case "invalid_proof":
return "invalid_proof";
}
};
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? new ServerAuthInvalidCredentialError({
diagnostic: "DPoP proof replayed.",
dpopFailureReason: "replay",
cause: error,
})
: new ServerAuthDpopReplayStateRecordError({
cause: error,
});
/** Checks a proof without recording it; `consume` records its jti so it cannot be replayed. */
export const checkRequestDpopProof = Effect.fn("dpop.checkRequestDpopProof")(function* (input: {
readonly request: HttpServerRequest.HttpServerRequest;
/** Overrides the `DPoP` header for requests that cannot carry one, such as a WebSocket upgrade. */
readonly proof?: string;
readonly expectedThumbprint?: string;
readonly expectedAccessToken?: string;
}) {
const proof = input.proof ?? input.request.headers.dpop;
const url = requestUrl(input.request);
if (Option.isNone(url)) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: "Invalid DPoP request URL.",
});
}
const now = yield* DateTime.now;
const result = verifyDpopProof({
proof,
method: input.request.method,
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
});
if (!result.ok) {
yield* Effect.annotateCurrentSpan({
"environment.dpop.failure_code": result.code,
});
return yield* new ServerAuthInvalidCredentialError({
diagnostic: result.reason,
dpopFailureReason: mapDpopFailureReason(result.code),
});
}
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const digest = yield* Digest.Digest;
const consume: Effect.Effect<void, ServerAuthInvalidCredentialError | ServerAuthInternalError> =
Effect.gen(function* () {
const replayKey = yield* digest
.digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`))
.pipe(
Effect.map(Base64Url.encode),
Effect.mapError(
(cause) =>
new ServerAuthDpopReplayKeyCalculationError({
cause,
}),
),
);
yield* secretStore
.create(
`${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`,
new TextEncoder().encode(
[
`thumbprint=${result.thumbprint}`,
`jti=${result.jti}`,
`iat=${result.iat}`,
`consumedAt=${DateTime.formatIso(now)}`,
].join("\n"),
),
)
.pipe(
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
Effect.gen(function* () {
const mapped = mapDpopReplayStoreError(error);
if (mapped._tag === "ServerAuthInvalidCredentialError") {
yield* Effect.annotateCurrentSpan({
"environment.dpop.failure_code": mapped.dpopFailureReason,
});
}
return yield* mapped;
}),
),
);
});
return { thumbprint: result.thumbprint, consume };
});
export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (
input: Parameters<typeof checkRequestDpopProof>[0],
) {
const proof = yield* checkRequestDpopProof(input);
yield* proof.consume;
return proof.thumbprint;
});