Open History to see the last commit
1import { p256 } from "@noble/curves/nist";
2import { sha256 } from "@noble/hashes/sha2";
3import * as Encoding from "effect/Encoding";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6
7import { stableStringify } from "./relaySigning.ts";
8
9const DPOP_TYP = "dpop+jwt";
10const DPOP_ALG = "ES256";
11const DEFAULT_MAX_AGE_SECONDS = 300;
12
13export const DpopPublicJwk = Schema.Struct({
14 kty: Schema.Literal("EC"),
15 crv: Schema.Literal("P-256"),
16 x: Schema.String.check(Schema.isNonEmpty()),
17 y: Schema.String.check(Schema.isNonEmpty()),
18});
19export type DpopPublicJwk = typeof DpopPublicJwk.Type;
20const isDpopPublicJwk = Schema.is(DpopPublicJwk);
21
22interface DpopJwtHeader {
23 readonly typ: string;
24 readonly alg: string;
25 readonly jwk: DpopPublicJwk;
26}
27
28interface DpopJwtPayload {
29 readonly htm: string;
30 readonly htu: string;
31 readonly jti: string;
32 readonly iat: number;
33 readonly ath?: string;
34}
35
36export type DpopVerificationResult =
37 | {
38 readonly ok: true;
39 readonly thumbprint: string;
40 readonly jti: string;
41 readonly iat: number;
42 }
43 | {
44 readonly ok: false;
45 readonly reason: string;
46 };
47
48function base64UrlToBytes(value: string): Uint8Array {
49 return Result.getOrThrow(Encoding.decodeBase64Url(value));
50}
51
52function decodeBase64UrlJson(value: string): unknown {
53 return JSON.parse(Result.getOrThrow(Encoding.decodeBase64UrlString(value))) as unknown;
54}
55
56function isDpopJwtHeader(value: unknown): value is DpopJwtHeader {
57 if (typeof value !== "object" || value === null) {
58 return false;
59 }
60 const record = value as Record<string, unknown>;
61 return (
62 record.typ === DPOP_TYP &&
63 record.alg === DPOP_ALG &&
64 typeof record.jwk === "object" &&
65 record.jwk !== null &&
66 !("d" in record.jwk) &&
67 isDpopPublicJwk(record.jwk)
68 );
69}
70
71function isDpopJwtPayload(value: unknown): value is DpopJwtPayload {
72 if (typeof value !== "object" || value === null) {
73 return false;
74 }
75 const record = value as Record<string, unknown>;
76 return (
77 typeof record.htm === "string" &&
78 record.htm.length > 0 &&
79 typeof record.htu === "string" &&
80 record.htu.length > 0 &&
81 typeof record.jti === "string" &&
82 record.jti.length > 0 &&
83 typeof record.iat === "number" &&
84 Number.isInteger(record.iat)
85 );
86}
87
88function dpopThumbprintInput(jwk: DpopPublicJwk): string {
89 return stableStringify({
90 crv: jwk.crv,
91 kty: jwk.kty,
92 x: jwk.x,
93 y: jwk.y,
94 });
95}
96
97export function normalizeDpopHtu(url: string): string | null {
98 try {
99 const parsed = new URL(url);
100 parsed.hash = "";
101 parsed.search = "";
102 return parsed.toString();
103 } catch {
104 return null;
105 }
106}
107
108export function computeDpopJwkThumbprint(jwk: DpopPublicJwk): string {
109 return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));
110}
111
112export function computeDpopAccessTokenHash(accessToken: string): string {
113 return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken)));
114}
115
116function publicKeyBytesFromJwk(jwk: DpopPublicJwk): Uint8Array {
117 const x = base64UrlToBytes(jwk.x);
118 const y = base64UrlToBytes(jwk.y);
119 if (x.length !== 32 || y.length !== 32) {
120 throw new Error("Invalid P-256 public key coordinate length.");
121 }
122 const publicKey = new Uint8Array(65);
123 publicKey[0] = 0x04;
124 publicKey.set(x, 1);
125 publicKey.set(y, 33);
126 return publicKey;
127}
128
129export function verifyDpopProof(input: {
130 readonly proof: string | null | undefined;
131 readonly method: string;
132 readonly url: string;
133 readonly nowEpochSeconds: number;
134 readonly expectedThumbprint?: string;
135 readonly expectedAccessToken?: string;
136 readonly maxAgeSeconds?: number;
137}): DpopVerificationResult {
138 if (!input.proof?.trim()) {
139 return { ok: false, reason: "Missing DPoP proof." };
140 }
141
142 const parts = input.proof.split(".");
143 if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
144 return { ok: false, reason: "Invalid DPoP compact JWT." };
145 }
146
147 try {
148 const header = decodeBase64UrlJson(parts[0]);
149 const payload = decodeBase64UrlJson(parts[1]);
150 if (!isDpopJwtHeader(header)) {
151 return { ok: false, reason: "Invalid DPoP JWT header." };
152 }
153 if (!isDpopJwtPayload(payload)) {
154 return { ok: false, reason: "Invalid DPoP JWT payload." };
155 }
156
157 const thumbprint = computeDpopJwkThumbprint(header.jwk);
158 if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {
159 return { ok: false, reason: "DPoP key thumbprint mismatch." };
160 }
161 if (payload.htm.toUpperCase() !== input.method.toUpperCase()) {
162 return { ok: false, reason: "DPoP method mismatch." };
163 }
164 const normalizedHtu = normalizeDpopHtu(input.url);
165 if (normalizedHtu === null || payload.htu !== normalizedHtu) {
166 return { ok: false, reason: "DPoP URL mismatch." };
167 }
168 if (input.expectedAccessToken) {
169 const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);
170 if (payload.ath !== expectedAth) {
171 return { ok: false, reason: "DPoP access token hash mismatch." };
172 }
173 }
174
175 const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;
176 if (
177 payload.iat > input.nowEpochSeconds + 5 ||
178 input.nowEpochSeconds - payload.iat > maxAgeSeconds
179 ) {
180 return { ok: false, reason: "DPoP proof is outside the allowed time window." };
181 }
182
183 const signature = base64UrlToBytes(parts[2]);
184 const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
185 const verified = p256.verify(signature, signatureInputHash, publicKeyBytesFromJwk(header.jwk), {
186 prehash: false,
187 format: "compact",
188 });
189 return verified
190 ? {
191 ok: true,
192 thumbprint,
193 jti: payload.jti,
194 iat: payload.iat,
195 }
196 : { ok: false, reason: "Invalid DPoP signature." };
197 } catch {
198 return { ok: false, reason: "Invalid DPoP proof." };
199 }
200}