The best way to control Claude Code, Codex and more from any computer or phone

main
ts 198 lines 7.41 KB
Raw
1 import * as Digest from "effect/crypto/Digest";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 import * as Effect from "effect/Effect";
4 import * as Base64Url from "effect/encoding/Base64Url";
5 import * as Hex from "effect/encoding/Hex";
6 import * as Result from "effect/Result";
7 import * as Schema from "effect/Schema";
8 import * as ExpoCrypto from "expo-crypto";
9 import { msg } from "gt-react-native";
10
11 import { m } from "../../i18n/messages";
12 import * as SecureStore from "expo-secure-store";
13 import { DpopProof } from "@t3tools/client-runtime/relay";
14 import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";
15 import * as Layer from "effect/Layer";
16
17 export class CloudDpopError extends Schema.TaggedError<CloudDpopError>()("CloudDpopError", {
18 message: Schema.String,
19 cause: Schema.optional(Schema.Defect()),
20 }) {}
21
22 function cloudDpopError(message: string) {
23 return (cause: unknown) => new CloudDpopError({ message, cause });
24 }
25
26 const DpopPrivateJwkSchema = Schema.Struct({
27 ...DpopPublicJwk.fields,
28 d: Schema.String,
29 });
30
31 const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);
32 const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
33 const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);
34
35 function toExpoDigestAlgorithm(algorithm: Digest.Algorithm): ExpoCrypto.CryptoDigestAlgorithm {
36 switch (algorithm.name) {
37 case "MD5":
38 return ExpoCrypto.CryptoDigestAlgorithm.MD5;
39 case "SHA-1":
40 return ExpoCrypto.CryptoDigestAlgorithm.SHA1;
41 case "SHA-256":
42 return ExpoCrypto.CryptoDigestAlgorithm.SHA256;
43 case "SHA-384":
44 return ExpoCrypto.CryptoDigestAlgorithm.SHA384;
45 case "SHA-512":
46 return ExpoCrypto.CryptoDigestAlgorithm.SHA512;
47 }
48 }
49
50 // Hermes has no SubtleCrypto, so Effect's WebCrypto layers cannot back these services.
51 const digest = (algorithm: Digest.Algorithm, data: Uint8Array) =>
52 Effect.promise(async () => {
53 const input = new Uint8Array(data.length);
54 input.set(data);
55 return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));
56 });
57
58 export const layer = Layer.mergeAll(
59 Layer.succeed(SecureRandom.SecureRandom, SecureRandom.make(ExpoCrypto.getRandomBytes)),
60 Layer.succeed(
61 Digest.Digest,
62 Digest.Digest.of({
63 digest,
64 digestHex: Effect.fn("Digest.Digest.digestHex")((algorithm, data) =>
65 Effect.map(digest(algorithm, data), Hex.encode),
66 ),
67 }),
68 ),
69 );
70
71 type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
72
73 export interface DpopProofKeyPair {
74 readonly privateJwk: DpopPrivateJwk;
75 readonly publicJwk: DpopPublicJwk;
76 }
77
78 const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
79
80 interface NativeDpopKeys {
81 /** A 32-byte private scalar followed by its 65-byte uncompressed public point. */
82 generateDpopKey(): Promise<Uint8Array>;
83 dpopKeyMatches(privateKey: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
84 /** ES256 over the signing input, as the raw 64-byte `r‖s` pair. */
85 signDpop(privateKey: Uint8Array, signingInput: Uint8Array): Promise<Uint8Array>;
86 }
87
88 // Platform crypto: in Hermes, @noble/curves blocks JS for about a second on its first P-256 key.
89 // Imported lazily: loading `expo` at module scope breaks Node tests that import this file.
90 const nativeDpopKeys = async () =>
91 (await import("expo")).requireNativeModule<NativeDpopKeys>("T3NativeControls");
92
93 function base64UrlToBytes(value: string): Uint8Array {
94 return Result.getOrThrow(Base64Url.decode(value));
95 }
96
97 function coordinateBytes(value: string): Uint8Array {
98 const bytes = base64UrlToBytes(value);
99 if (bytes.length !== 32 || Base64Url.encode(bytes) !== value) {
100 throw new Error(m(msg("DPoP key coordinate is not 32 canonical bytes.")));
101 }
102 return bytes;
103 }
104
105 function uncompressedPublicKeyFromJwk(jwk: DpopPublicJwk): Uint8Array {
106 const publicKey = new Uint8Array(65);
107 publicKey[0] = 0x04;
108 publicKey.set(coordinateBytes(jwk.x), 1);
109 publicKey.set(coordinateBytes(jwk.y), 33);
110 return publicKey;
111 }
112
113 function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
114 if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
115 throw new Error(m(msg("Generated DPoP public key is not an uncompressed P-256 point.")));
116 }
117 return {
118 kty: "EC",
119 crv: "P-256",
120 x: Base64Url.encode(publicKey.slice(1, 33)),
121 y: Base64Url.encode(publicKey.slice(33, 65)),
122 };
123 }
124
125 function privateJwkFromPrivateKey(
126 privateKey: Uint8Array,
127 publicJwk: DpopPublicJwk,
128 ): DpopPrivateJwk {
129 return { ...publicJwk, d: Base64Url.encode(privateKey) };
130 }
131
132 export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(
133 function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError> {
134 const key = yield* Effect.tryPromise({
135 try: async () => (await nativeDpopKeys()).generateDpopKey(),
136 catch: cloudDpopError(m(msg("Could not generate the DPoP key pair."))),
137 });
138 const publicJwk = yield* Effect.try({
139 try: () => publicJwkFromUncompressedPublicKey(key.slice(32)),
140 catch: cloudDpopError(m(msg("Generated DPoP public key is invalid."))),
141 });
142 return { privateJwk: privateJwkFromPrivateKey(key.slice(0, 32), publicJwk), publicJwk };
143 },
144 );
145
146 export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(
147 function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError> {
148 const stored = yield* Effect.tryPromise({
149 try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
150 catch: cloudDpopError(m(msg("Could not read the DPoP proof key."))),
151 });
152 if (stored) {
153 const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
154 Effect.mapError(cloudDpopError(m(msg("Stored DPoP proof key is invalid.")))),
155 );
156 const { d, ...publicJwk } = storedPrivateJwk;
157 const matches = yield* Effect.tryPromise({
158 try: async () =>
159 (await nativeDpopKeys()).dpopKeyMatches(
160 base64UrlToBytes(d),
161 uncompressedPublicKeyFromJwk(publicJwk),
162 ),
163 catch: cloudDpopError(m(msg("Stored DPoP proof key is invalid."))),
164 });
165 if (!matches) {
166 return yield* new CloudDpopError({ message: m(msg("Stored DPoP proof key is invalid.")) });
167 }
168 return { privateJwk: storedPrivateJwk, publicJwk };
169 }
170 const generated = yield* generateDpopProofKeyPair();
171 const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
172 Effect.mapError(cloudDpopError(m(msg("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(m(msg("Could not store the DPoP proof key."))),
177 });
178 return generated;
179 },
180 );
181
182 /** The installation's DPoP key, signing with the platform's P-256. */
183 export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(function* () {
184 const keyPair = yield* loadOrCreateDpopProofKeyPair();
185 const privateKey = yield* Effect.try({
186 try: () => base64UrlToBytes(keyPair.privateJwk.d),
187 catch: cloudDpopError(m(msg("Could not import DPoP private key."))),
188 });
189 return {
190 publicJwk: keyPair.publicJwk,
191 sign: (signingInput) =>
192 Effect.tryPromise({
193 try: async () => (await nativeDpopKeys()).signDpop(privateKey, signingInput),
194 catch: (cause) =>
195 new DpopProof.DpopProofError({ message: m(msg("Could not sign DPoP proof.")), cause }),
196 }),
197 } satisfies DpopProof.DpopProofKey;
198 });