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

dpop.ts

188 lines5.7 KB

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