Open History to see the last commit
1import * as Digest from "effect/crypto/Digest";
2import * as SecureRandom from "effect/crypto/SecureRandom";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as Base64Url from "effect/encoding/Base64Url";
6import * as Hex from "effect/encoding/Hex";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import * as ExpoCrypto from "expo-crypto";
10import * as SecureStore from "expo-secure-store";
11import { p256 } from "@noble/curves/nist";
12import { DpopProof } from "@t3tools/client-runtime/relay";
13import { DpopPublicJwk } 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
34function toExpoDigestAlgorithm(algorithm: Digest.Algorithm): ExpoCrypto.CryptoDigestAlgorithm {
35 switch (algorithm.name) {
36 case "MD5":
37 return ExpoCrypto.CryptoDigestAlgorithm.MD5;
38 case "SHA-1":
39 return ExpoCrypto.CryptoDigestAlgorithm.SHA1;
40 case "SHA-256":
41 return ExpoCrypto.CryptoDigestAlgorithm.SHA256;
42 case "SHA-384":
43 return ExpoCrypto.CryptoDigestAlgorithm.SHA384;
44 case "SHA-512":
45 return ExpoCrypto.CryptoDigestAlgorithm.SHA512;
46 }
47}
48
49// Hermes has no SubtleCrypto, so Effect's WebCrypto layers cannot back these services.
50const digest = (algorithm: Digest.Algorithm, data: Uint8Array) =>
51 Effect.promise(async () => {
52 const input = new Uint8Array(data.length);
53 input.set(data);
54 return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));
55 });
56
57export const layer = Layer.mergeAll(
58 Layer.succeed(SecureRandom.SecureRandom, SecureRandom.make(ExpoCrypto.getRandomBytes)),
59 Layer.succeed(
60 Digest.Digest,
61 Digest.Digest.of({
62 digest,
63 digestHex: (algorithm, data) => Effect.map(digest(algorithm, data), Hex.encode),
64 }),
65 ),
66);
67
68type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
69
70export interface DpopProofKeyPair {
71 readonly privateJwk: DpopPrivateJwk;
72 readonly publicJwk: DpopPublicJwk;
73}
74
75const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
76
77function base64UrlToBytes(value: string): Uint8Array {
78 return Result.getOrThrow(Base64Url.decode(value));
79}
80
81function sha256Digest(
82 data: Uint8Array,
83 message: string,
84): Effect.Effect<Uint8Array, CloudDpopError, Digest.Digest> {
85 return Digest.Digest.pipe(
86 Effect.flatMap((service) => service.digest(Digest.sha256, data)),
87 Effect.mapError(cloudDpopError(message)),
88 );
89}
90
91function secureRandomBytes(
92 byteCount: number,
93 message: string,
94): Effect.Effect<Uint8Array, CloudDpopError, SecureRandom.SecureRandom> {
95 return SecureRandom.SecureRandom.pipe(
96 Effect.flatMap((random) => random.randomBytes(byteCount)),
97 Effect.mapError(cloudDpopError(message)),
98 );
99}
100
101function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
102 if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
103 throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
104 }
105 return {
106 kty: "EC",
107 crv: "P-256",
108 x: Base64Url.encode(publicKey.slice(1, 33)),
109 y: Base64Url.encode(publicKey.slice(33, 65)),
110 };
111}
112
113function privateJwkFromPrivateKey(
114 privateKey: Uint8Array,
115 publicJwk: DpopPublicJwk,
116): DpopPrivateJwk {
117 return { ...publicJwk, d: Base64Url.encode(privateKey) };
118}
119
120export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(
121 function* (): Effect.fn.Return<
122 DpopProofKeyPair,
123 CloudDpopError,
124 SecureRandom.SecureRandom | Digest.Digest
125 > {
126 let privateKey: Uint8Array;
127 do {
128 privateKey = yield* secureRandomBytes(
129 p256.CURVE.nByteLength,
130 "Could not generate DPoP key pair randomness.",
131 );
132 } while (!p256.utils.isValidPrivateKey(privateKey));
133 const publicJwk = yield* Effect.try({
134 try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
135 catch: cloudDpopError("Generated DPoP public key is invalid."),
136 });
137 return { privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk), publicJwk };
138 },
139);
140
141export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(
142 function* (): Effect.fn.Return<
143 DpopProofKeyPair,
144 CloudDpopError,
145 SecureRandom.SecureRandom | Digest.Digest
146 > {
147 const stored = yield* Effect.tryPromise({
148 try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
149 catch: cloudDpopError("Could not read the DPoP proof key."),
150 });
151 if (stored) {
152 const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
153 Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
154 );
155 const restored = yield* Effect.try({
156 try: () => {
157 const privateKey = base64UrlToBytes(storedPrivateJwk.d);
158 const publicJwk = publicJwkFromUncompressedPublicKey(
159 p256.getPublicKey(privateKey, false),
160 );
161 if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
162 throw new Error("Stored DPoP key does not match its public key.");
163 }
164 return { privateJwk: storedPrivateJwk, publicJwk };
165 },
166 catch: cloudDpopError("Stored DPoP proof key is invalid."),
167 });
168 return restored;
169 }
170 const generated = yield* generateDpopProofKeyPair();
171 const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
172 Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
173 );
174 yield* Effect.tryPromise({
175 try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
176 catch: cloudDpopError("Could not store the DPoP proof key."),
177 });
178 return generated;
179 },
180);
181
182/** The installation's DPoP key, signing with @noble/curves over an Expo SHA-256 digest. */
183export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(function* () {
184 const digest = yield* Digest.Digest;
185 const keyPair = yield* loadOrCreateDpopProofKeyPair();
186 const privateKey = yield* Effect.try({
187 try: () => base64UrlToBytes(keyPair.privateJwk.d),
188 catch: cloudDpopError("Could not import DPoP private key."),
189 });
190 return {
191 publicJwk: keyPair.publicJwk,
192 sign: (signingInput) =>
193 sha256Digest(signingInput, "Could not hash DPoP signing input.").pipe(
194 Effect.provideService(Digest.Digest, digest),
195 Effect.flatMap((hash) =>
196 Effect.try({
197 try: () => p256.sign(hash, privateKey, { prehash: false }).toCompactRawBytes(),
198 catch: cloudDpopError("Could not sign DPoP proof."),
199 }),
200 ),
201 Effect.mapError(
202 (cause) => new DpopProof.DpopProofError({ message: "Could not sign DPoP proof.", cause }),
203 ),
204 ),
205 } satisfies DpopProof.DpopProofKey;
206});