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

dpop.ts

207 lines7.3 KB

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