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

dpop.ts

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