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