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

dpop.ts

200 lines6.3 KB

1import { p256 } from "@noble/curves/nist";
2import { sha256 } from "@noble/hashes/sha2";
3import * as Base64Url from "effect/encoding/Base64Url";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7​
8import { DpopPublicJwk as DpopPublicJwkSchema, normalizeDpopHtu } from "./dpopCommon.ts";
9import type { DpopPublicJwk as DpopPublicJwkType } from "./dpopCommon.ts";
10import { stableStringify } from "./relaySigning.ts";
11​
12const DPOP_TYP = "dpop+jwt";
13const DPOP_ALG = "ES256";
14/**
15 * How far a proof's `iat` may sit from the verifier's clock, in either direction.
16 * Proofs carry the client's clock, so this also bounds tolerated clock skew.
17 */
18export const DPOP_MAX_CLOCK_SKEW_SECONDS = 300;
19​
20export const DpopPublicJwk = DpopPublicJwkSchema;
21export type DpopPublicJwk = DpopPublicJwkType;
22export { normalizeDpopHtu };
23​
24export const DpopVerificationFailureCode = Schema.Literals([
25 "missing_proof",
26 "malformed_proof",
27 "key_mismatch",
28 "method_mismatch",
29 "url_mismatch",
30 "access_token_hash_mismatch",
31 "time_window",
32 "invalid_signature",
33 "invalid_proof",
34]);
35export type DpopVerificationFailureCode = typeof DpopVerificationFailureCode.Type;
36​
37const DpopJwtHeaderPublicJwk = Schema.Struct({
38 ...DpopPublicJwkSchema.fields,
39 d: Schema.optionalKey(Schema.Never),
40});
41​
42const DpopJwtHeaderJson = Schema.fromJsonString(
43 Schema.Struct({
44 typ: Schema.Literal(DPOP_TYP),
45 alg: Schema.Literal(DPOP_ALG),
46 jwk: DpopJwtHeaderPublicJwk,
47 }),
48);
49const decodeDpopJwtHeaderJson = Schema.decodeUnknownOption(DpopJwtHeaderJson);
50​
51const DpopJwtPayloadJson = Schema.fromJsonString(
52 Schema.Struct({
53 htm: Schema.String.check(Schema.isNonEmpty()),
54 htu: Schema.String.check(Schema.isNonEmpty()),
55 jti: Schema.String.check(Schema.isNonEmpty()),
56 iat: Schema.Int,
57 ath: Schema.optionalKey(Schema.String),
58 }),
59);
60const decodeDpopJwtPayloadJson = Schema.decodeUnknownOption(DpopJwtPayloadJson);
61​
62export type DpopVerificationResult =
63 | {
64 readonly ok: true;
65 readonly thumbprint: string;
66 readonly jti: string;
67 readonly iat: number;
68 }
69 | {
70 readonly ok: false;
71 readonly code: DpopVerificationFailureCode;
72 readonly reason: string;
73 };
74​
75function base64UrlToBytes(value: string): Uint8Array {
76 return Result.getOrThrow(Base64Url.decode(value));
78​
79function decodeBase64UrlDpopJwtHeader(value: string) {
80 return decodeDpopJwtHeaderJson(Result.getOrThrow(Base64Url.decodeString(value)));
82​
83function decodeBase64UrlDpopJwtPayload(value: string) {
84 return decodeDpopJwtPayloadJson(Result.getOrThrow(Base64Url.decodeString(value)));
86​
87function dpopThumbprintInput(jwk: DpopPublicJwkType): string {
88 return stableStringify({
89 crv: jwk.crv,
90 kty: jwk.kty,
91 x: jwk.x,
92 y: jwk.y,
93 });
95​
96export function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string {
97 return Base64Url.encode(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));
99​
100export function computeDpopAccessTokenHash(accessToken: string): string {
101 return Base64Url.encode(sha256(new TextEncoder().encode(accessToken)));
103​
104function publicKeyBytesFromJwk(jwk: DpopPublicJwkType): Uint8Array {
105 const x = base64UrlToBytes(jwk.x);
106 const y = base64UrlToBytes(jwk.y);
107 if (x.length !== 32 || y.length !== 32) {
108 throw new Error("Invalid P-256 public key coordinate length.");
109 }
110 const publicKey = new Uint8Array(65);
111 publicKey[0] = 0x04;
112 publicKey.set(x, 1);
113 publicKey.set(y, 33);
114 return publicKey;
116​
117export function verifyDpopProof(input: {
118 readonly proof: string | null | undefined;
119 readonly method: string;
120 readonly url: string;
121 readonly nowEpochSeconds: number;
122 readonly expectedThumbprint?: string;
123 readonly expectedAccessToken?: string;
124 readonly maxAgeSeconds?: number;
125}): DpopVerificationResult {
126 if (!input.proof?.trim()) {
127 return { ok: false, code: "missing_proof", reason: "Missing DPoP proof." };
128 }
129​
130 const parts = input.proof.split(".");
131 if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
132 return { ok: false, code: "malformed_proof", reason: "Invalid DPoP compact JWT." };
133 }
134​
135 try {
136 const header = decodeBase64UrlDpopJwtHeader(parts[0]);
137 const payload = decodeBase64UrlDpopJwtPayload(parts[1]);
138 if (Option.isNone(header)) {
139 return { ok: false, code: "malformed_proof", reason: "Invalid DPoP JWT header." };
140 }
141 if (Option.isNone(payload)) {
142 return { ok: false, code: "malformed_proof", reason: "Invalid DPoP JWT payload." };
143 }
144​
145 const thumbprint = computeDpopJwkThumbprint(header.value.jwk);
146 if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {
147 return { ok: false, code: "key_mismatch", reason: "DPoP key thumbprint mismatch." };
148 }
149 if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {
150 return { ok: false, code: "method_mismatch", reason: "DPoP method mismatch." };
151 }
152 const normalizedHtu = normalizeDpopHtu(input.url);
153 if (normalizedHtu === null || payload.value.htu !== normalizedHtu) {
154 return { ok: false, code: "url_mismatch", reason: "DPoP URL mismatch." };
155 }
156 if (input.expectedAccessToken) {
157 const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);
158 if (payload.value.ath !== expectedAth) {
159 return {
160 ok: false,
161 code: "access_token_hash_mismatch",
162 reason: "DPoP access token hash mismatch.",
163 };
164 }
165 }
166​
167 const signature = base64UrlToBytes(parts[2]);
168 const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
169 const verified = p256.verify(
170 signature,
171 signatureInputHash,
172 publicKeyBytesFromJwk(header.value.jwk),
173 {
174 prehash: false,
175 format: "compact",
176 },
177 );
178 if (!verified) {
179 return { ok: false, code: "invalid_signature", reason: "Invalid DPoP signature." };
180 }
181​
182 const maxAgeSeconds = input.maxAgeSeconds ?? DPOP_MAX_CLOCK_SKEW_SECONDS;
183 if (Math.abs(input.nowEpochSeconds - payload.value.iat) > maxAgeSeconds) {
184 return {
185 ok: false,
186 code: "time_window",
187 reason: "DPoP proof is outside the allowed time window.",
188 };
189 }
190​
191 return {
192 ok: true,
193 thumbprint,
194 jti: payload.value.jti,
195 iat: payload.value.iat,
196 };
197 } catch {
198 return { ok: false, code: "invalid_proof", reason: "Invalid DPoP proof." };
199 }