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