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

dpop.ts

290 lines9.4 KB

1import * as Clock from "effect/Clock";
2import * as Crypto from "effect/Crypto";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as Base64Url from "effect/encoding/Base64Url";
6import * as Result from "effect/Result";
7import * as Schema from "effect/Schema";
8import * as ExpoCrypto from "expo-crypto";
9import * as SecureStore from "expo-secure-store";
10import { p256 } from "@noble/curves/nist";
11import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
12import * as Layer from "effect/Layer";
13​
14export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
15 readonly message: string;
16 readonly cause?: unknown;
17}> {}
18​
19function cloudDpopError(message: string) {
20 return (cause: unknown) => new CloudDpopError({ message, cause });
22​
23const DpopPrivateJwkSchema = Schema.Struct({
24 ...DpopPublicJwk.fields,
25 d: Schema.String,
26});
27​
28const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);
29const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
30const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);
31​
32const DpopJwtHeaderJson = Schema.fromJsonString(
33 Schema.Struct({
34 typ: Schema.Literal("dpop+jwt"),
35 alg: Schema.Literal("ES256"),
36 jwk: DpopPublicJwk,
37 }),
38);
39​
40const DpopJwtPayloadJson = Schema.fromJsonString(
41 Schema.Struct({
42 htm: Schema.String,
43 htu: Schema.String,
44 jti: Schema.String,
45 iat: Schema.Int,
46 ath: Schema.optionalKey(Schema.String),
47 }),
48);
49​
50const encodeDpopJwtHeaderJson = Schema.encodeEffect(DpopJwtHeaderJson);
51const encodeDpopJwtPayloadJson = Schema.encodeEffect(DpopJwtPayloadJson);
52​
53function toExpoDigestAlgorithm(
54 algorithm: Crypto.DigestAlgorithm,
55): ExpoCrypto.CryptoDigestAlgorithm {
56 switch (algorithm) {
57 case "SHA-1":
58 return ExpoCrypto.CryptoDigestAlgorithm.SHA1;
59 case "SHA-256":
60 return ExpoCrypto.CryptoDigestAlgorithm.SHA256;
61 case "SHA-384":
62 return ExpoCrypto.CryptoDigestAlgorithm.SHA384;
63 case "SHA-512":
64 return ExpoCrypto.CryptoDigestAlgorithm.SHA512;
65 }
67​
68export const layer = Layer.succeed(
69 Crypto.Crypto,
70 Crypto.make({
71 randomBytes: ExpoCrypto.getRandomBytes,
72 digest: (algorithm, data) =>
73 Effect.promise(async () => {
74 const input = new Uint8Array(data.length);
75 input.set(data);
76 return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));
77 }),
78 }),
79);
80​
81type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
82​
83export interface DpopProofKeyPair {
84 readonly privateJwk: DpopPrivateJwk;
85 readonly publicJwk: DpopPublicJwk;
86 readonly thumbprint: string;
88​
89const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
90​
91function base64UrlToBytes(value: string): Uint8Array {
92 return Result.getOrThrow(Base64Url.decode(value));
94​
95function sha256Digest(
96 data: Uint8Array,
97 message: string,
98): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
99 return Crypto.Crypto.pipe(
100 Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
101 Effect.mapError(cloudDpopError(message)),
102 );
104​
105function base64UrlSha256(
106 data: Uint8Array,
107 message: string,
108): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
109 return sha256Digest(data, message).pipe(Effect.map(Base64Url.encode));
111​
112function dpopThumbprintInput(jwk: DpopPublicJwk): string {
113 return JSON.stringify({
114 crv: jwk.crv,
115 kty: jwk.kty,
116 x: jwk.x,
117 y: jwk.y,
118 });
120​
121function computeDpopJwkThumbprintEffect(
122 jwk: DpopPublicJwk,
123): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
124 return base64UrlSha256(
125 new TextEncoder().encode(dpopThumbprintInput(jwk)),
126 "Could not hash the DPoP public key thumbprint.",
127 );
129​
130function computeDpopAccessTokenHashEffect(
131 accessToken: string,
132): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {
133 return base64UrlSha256(
134 new TextEncoder().encode(accessToken),
135 "Could not hash the DPoP access token.",
136 );
138​
139function secureRandomBytes(
140 byteCount: number,
141 message: string,
142): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
143 return Crypto.Crypto.pipe(
144 Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
145 Effect.mapError(cloudDpopError(message)),
146 );
148​
149function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
150 if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
151 throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
152 }
153 return {
154 kty: "EC",
155 crv: "P-256",
156 x: Base64Url.encode(publicKey.slice(1, 33)),
157 y: Base64Url.encode(publicKey.slice(33, 65)),
158 };
160​
161function privateJwkFromPrivateKey(
162 privateKey: Uint8Array,
163 publicJwk: DpopPublicJwk,
164): DpopPrivateJwk {
165 return { ...publicJwk, d: Base64Url.encode(privateKey) };
167​
168export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(
169 function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {
170 let privateKey: Uint8Array;
171 do {
172 privateKey = yield* secureRandomBytes(
173 p256.CURVE.nByteLength,
174 "Could not generate DPoP key pair randomness.",
175 );
176 } while (!p256.utils.isValidPrivateKey(privateKey));
177 const publicJwk = yield* Effect.try({
178 try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
179 catch: cloudDpopError("Generated DPoP public key is invalid."),
180 });
181 const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
182 return {
183 privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
184 publicJwk,
185 thumbprint,
186 };
187 },
188);
189​
190export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(
191 function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {
192 const stored = yield* Effect.tryPromise({
193 try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
194 catch: cloudDpopError("Could not read the DPoP proof key."),
195 });
196 if (stored) {
197 const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
198 Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
199 );
200 const restored = yield* Effect.try({
201 try: () => {
202 const privateKey = base64UrlToBytes(storedPrivateJwk.d);
203 const publicJwk = publicJwkFromUncompressedPublicKey(
204 p256.getPublicKey(privateKey, false),
205 );
206 if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
207 throw new Error("Stored DPoP key does not match its public key.");
208 }
209 return { privateJwk: storedPrivateJwk, publicJwk };
210 },
211 catch: cloudDpopError("Stored DPoP proof key is invalid."),
212 });
213 const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
214 return {
215 ...restored,
216 thumbprint,
217 };
218 }
219 const generated = yield* generateDpopProofKeyPair();
220 const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
221 Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
222 );
223 yield* Effect.tryPromise({
224 try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
225 catch: cloudDpopError("Could not store the DPoP proof key."),
226 });
227 return generated;
228 },
229);
230​
231function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
232 const normalized = normalizeDpopHtu(url);
233 return normalized
234 ? Effect.succeed(normalized)
235 : Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
237​
238export const createDpopProof = Effect.fn("dpop.createDpopProof")(function* (input: {
239 readonly method: string;
240 readonly url: string;
241 readonly accessToken?: string;
242 readonly proofKey?: DpopProofKeyPair;
243}): Effect.fn.Return<
244 { readonly proof: string; readonly thumbprint: string },
245 CloudDpopError,
246 Crypto.Crypto
247> {
248 const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
249 const privateKey = yield* Effect.try({
250 try: () => base64UrlToBytes(keyPair.privateJwk.d),
251 catch: cloudDpopError("Could not import DPoP private key."),
252 });
253 const nowMs = yield* Clock.currentTimeMillis;
254 const jti = yield* Crypto.Crypto.pipe(
255 Effect.flatMap((crypto) => crypto.randomUUIDv4()),
256 Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
257 );
258 const htu = yield* normalizeHtu(input.url);
259 const header = yield* encodeDpopJwtHeaderJson({
260 typ: "dpop+jwt",
261 alg: "ES256",
262 jwk: keyPair.publicJwk,
263 }).pipe(
264 Effect.map(Base64Url.encode),
265 Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
266 );
267 const ath = input.accessToken ? yield* computeDpopAccessTokenHashEffect(input.accessToken) : null;
268 const payload = yield* encodeDpopJwtPayloadJson({
269 htm: input.method.toUpperCase(),
270 htu,
271 jti,
272 iat: Math.floor(nowMs / 1_000),
273 ...(ath ? { ath } : {}),
274 }).pipe(
275 Effect.map(Base64Url.encode),
276 Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
277 );
278 const signatureInputHash = yield* sha256Digest(
279 new TextEncoder().encode(`${header}.${payload}`),
280 "Could not hash DPoP signing input.",
281 );
282 const signature = yield* Effect.try({
283 try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
284 catch: cloudDpopError("Could not sign DPoP proof."),
285 });
286 return {
287 proof: `${header}.${payload}.${Base64Url.encode(signature)}`,
288 thumbprint: keyPair.thumbprint,
289 };
290});