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

main
ts 167 lines 6.1 KB
Raw
1 import { msg } from "gt-react";
2 import { m } from "../i18n/messages";
3 import { DpopProof } from "@t3tools/client-runtime/relay";
4 import { computeDpopJwkThumbprint, DpopPublicJwk } from "@t3tools/shared/dpop";
5 import * as Digest from "effect/crypto/Digest";
6 import * as SecureRandom from "effect/crypto/SecureRandom";
7 import * as Signature from "effect/crypto/Signature";
8 import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
10 import * as Schema from "effect/Schema";
11
12 export interface BrowserDpopKey {
13 readonly privateKey: CryptoKey;
14 readonly publicJwk: DpopPublicJwk;
15 readonly thumbprint: string;
16 }
17
18 export class BrowserDpopError extends Schema.TaggedError<BrowserDpopError>()("BrowserDpopError", {
19 message: Schema.String,
20 cause: Schema.optional(Schema.Defect()),
21 }) {}
22
23 const isBrowserDpopError = Schema.is(BrowserDpopError);
24
25 const DPOP_DATABASE_NAME = "t3code:cloud-auth";
26 const DPOP_DATABASE_VERSION = 1;
27 const DPOP_KEY_STORE_NAME = "keys";
28 const DPOP_KEY_ID = "relay-dpop-proof-key";
29 const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);
30
31 export const layer = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
32 Layer.provideMerge(SecureRandom.layerWebCrypto),
33 );
34
35 function dpopError(message: string, cause?: unknown) {
36 return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });
37 }
38
39 function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {
40 return Effect.callback<IDBDatabase, BrowserDpopError>((resume) => {
41 const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION);
42 request.addEventListener("error", () =>
43 resume(
44 Effect.fail(
45 dpopError(m(msg("Could not open DPoP key storage.")), request.error ?? undefined),
46 ),
47 ),
48 );
49 request.addEventListener("upgradeneeded", () => {
50 if (!request.result.objectStoreNames.contains(DPOP_KEY_STORE_NAME)) {
51 request.result.createObjectStore(DPOP_KEY_STORE_NAME);
52 }
53 });
54 request.addEventListener("success", () => resume(Effect.succeed(request.result)));
55 });
56 }
57
58 function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null, BrowserDpopError> {
59 if (typeof indexedDB === "undefined") {
60 return Effect.succeed(null);
61 }
62 return Effect.acquireUseRelease(
63 openDpopDatabase(),
64 (database) =>
65 Effect.callback<BrowserDpopKey | null, BrowserDpopError>((resume) => {
66 const request = database
67 .transaction(DPOP_KEY_STORE_NAME, "readonly")
68 .objectStore(DPOP_KEY_STORE_NAME)
69 .get(DPOP_KEY_ID);
70 request.addEventListener("error", () =>
71 resume(
72 Effect.fail(dpopError(m(msg("Could not read DPoP key.")), request.error ?? undefined)),
73 ),
74 );
75 request.addEventListener("success", () =>
76 resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)),
77 );
78 }),
79 (database) => Effect.sync(() => database.close()),
80 );
81 }
82
83 function writeStoredBrowserDpopKey(key: BrowserDpopKey): Effect.Effect<void, BrowserDpopError> {
84 if (typeof indexedDB === "undefined") {
85 return Effect.void;
86 }
87 return Effect.acquireUseRelease(
88 openDpopDatabase(),
89 (database) =>
90 Effect.callback<void, BrowserDpopError>((resume) => {
91 const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite");
92 transaction.addEventListener("error", () =>
93 resume(
94 Effect.fail(
95 dpopError(m(msg("Could not write DPoP key.")), transaction.error ?? undefined),
96 ),
97 ),
98 );
99 transaction.addEventListener("complete", () => resume(Effect.void));
100 transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID);
101 }),
102 (database) => Effect.sync(() => database.close()),
103 );
104 }
105
106 const generateBrowserDpopKey = Effect.gen(function* () {
107 const generated = yield* Effect.tryPromise({
108 try: () =>
109 crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
110 "sign",
111 "verify",
112 ]) as Promise<CryptoKeyPair>,
113 catch: (cause) => dpopError(m(msg("Could not generate DPoP proof key.")), cause),
114 });
115 const privateJwk = yield* Effect.tryPromise({
116 try: () => crypto.subtle.exportKey("jwk", generated.privateKey),
117 catch: (cause) => dpopError(m(msg("Could not export DPoP private key.")), cause),
118 });
119 const publicJwk = yield* Effect.tryPromise({
120 try: () => crypto.subtle.exportKey("jwk", generated.publicKey),
121 catch: (cause) => dpopError(m(msg("Could not export DPoP public key.")), cause),
122 }).pipe(
123 Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),
124 Effect.mapError((cause) =>
125 isBrowserDpopError(cause)
126 ? cause
127 : dpopError(m(msg("Generated DPoP public key is invalid.")), cause),
128 ),
129 );
130 const privateKey = yield* Effect.tryPromise({
131 try: () =>
132 crypto.subtle.importKey("jwk", privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [
133 "sign",
134 ]),
135 catch: (cause) => dpopError(m(msg("Could not import DPoP private key.")), cause),
136 });
137 return {
138 privateKey,
139 publicJwk,
140 thumbprint: computeDpopJwkThumbprint(publicJwk),
141 };
142 });
143
144 /** The stored key, or a new one persisted on first use, as a DPoP proof key. */
145 export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(function* () {
146 const signature = yield* Signature.Signature;
147 const stored = yield* readStoredBrowserDpopKey();
148 const browserKey = stored ?? (yield* generateBrowserDpopKey);
149 if (stored === null) yield* writeStoredBrowserDpopKey(browserKey);
150 const privateKey = yield* Signature.privateKeyFromCryptoKey(
151 Signature.ecdsaP256,
152 browserKey.privateKey,
153 ).pipe(Effect.mapError((cause) => dpopError(m(msg("Could not load DPoP proof key.")), cause)));
154 return {
155 publicJwk: browserKey.publicJwk,
156 sign: (signingInput) =>
157 signature.sign(privateKey, signingInput).pipe(
158 Effect.mapError(
159 (cause) =>
160 new DpopProof.DpopProofError({
161 message: m(msg("Could not sign DPoP proof.")),
162 cause,
163 }),
164 ),
165 ),
166 } satisfies DpopProof.DpopProofKey;
167 });