The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // RFC 9449 DPoP proofs for relay requests. Platforms supply the key: web keeps a |
| 2 | // non-extractable WebCrypto key, mobile signs with the platform's P-256 through a native module. |
| 3 | import { msg } from "gt-i18n"; |
| 4 | import { MarkedText, translatableMessage } from "../errors/translatable.ts"; |
| 5 | import { normalizeDpopHtu, type DpopPublicJwk } from "@t3tools/shared/dpopCommon"; |
| 6 | import * as Cache from "effect/Cache"; |
| 7 | import * as Clock from "effect/Clock"; |
| 8 | import * as Digest from "effect/crypto/Digest"; |
| 9 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 10 | import * as Schema from "effect/Schema"; |
| 11 | import * as Duration from "effect/Duration"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as Base64Url from "effect/encoding/Base64Url"; |
| 14 | import * as Exit from "effect/Exit"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | |
| 17 | import { |
| 18 | ManagedRelayDpopKeyLoadError, |
| 19 | ManagedRelayDpopProofCreationError, |
| 20 | ManagedRelayDpopSigner, |
| 21 | } from "./managedRelay.ts"; |
| 22 | |
| 23 | export class DpopProofError extends Schema.TaggedError<DpopProofError>()("DpopProofError", { |
| 24 | message: Schema.String, |
| 25 | i18nMessage: Schema.optionalKey(MarkedText), |
| 26 | cause: Schema.optional(Schema.Defect()), |
| 27 | }) {} |
| 28 | |
| 29 | /** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */ |
| 30 | export interface DpopProofKey { |
| 31 | readonly publicJwk: DpopPublicJwk; |
| 32 | readonly sign: (signingInput: Uint8Array) => Effect.Effect<Uint8Array, DpopProofError>; |
| 33 | } |
| 34 | |
| 35 | const utf8 = (value: string) => new TextEncoder().encode(value); |
| 36 | const encodeSegment = (value: unknown) => Base64Url.encode(utf8(JSON.stringify(value))); |
| 37 | |
| 38 | const sha256Base64Url = (data: Uint8Array) => |
| 39 | Effect.flatMap(Digest.Digest, (digest) => digest.digest(Digest.sha256, data)).pipe( |
| 40 | Effect.map(Base64Url.encode), |
| 41 | ); |
| 42 | |
| 43 | /** RFC 7638 thumbprint: SHA-256 over the required members in lexicographic order. */ |
| 44 | export const thumbprint = (jwk: DpopPublicJwk) => |
| 45 | sha256Base64Url(utf8(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }))); |
| 46 | |
| 47 | export const createProof = Effect.fn("DpopProof.createProof")(function* (input: { |
| 48 | readonly method: string; |
| 49 | readonly url: string; |
| 50 | readonly accessToken?: string | undefined; |
| 51 | readonly key: DpopProofKey; |
| 52 | }) { |
| 53 | const htu = normalizeDpopHtu(input.url); |
| 54 | if (htu === null) |
| 55 | return yield* new DpopProofError(translatableMessage(msg("DPoP URL is invalid."))); |
| 56 | const random = yield* SecureRandom.SecureRandom; |
| 57 | const header = encodeSegment({ typ: "dpop+jwt", alg: "ES256", jwk: input.key.publicJwk }); |
| 58 | const payload = encodeSegment({ |
| 59 | htm: input.method.toUpperCase(), |
| 60 | htu, |
| 61 | jti: yield* random.uuidV4(), |
| 62 | iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000), |
| 63 | ...(input.accessToken ? { ath: yield* sha256Base64Url(utf8(input.accessToken)) } : {}), |
| 64 | }); |
| 65 | const signature = yield* input.key.sign(utf8(`${header}.${payload}`)); |
| 66 | return `${header}.${payload}.${Base64Url.encode(signature)}`; |
| 67 | }); |
| 68 | |
| 69 | /** A relay DPoP signer that loads its key once and keeps it; a failed load is retried. */ |
| 70 | export const layerSigner = <E, R>(options: { |
| 71 | readonly keyStore: ManagedRelayDpopKeyLoadError["keyStore"]; |
| 72 | readonly loadOrCreateKey: Effect.Effect<DpopProofKey, E, R>; |
| 73 | }) => |
| 74 | Layer.effect( |
| 75 | ManagedRelayDpopSigner, |
| 76 | Effect.gen(function* () { |
| 77 | const random = yield* SecureRandom.SecureRandom; |
| 78 | const digest = yield* Digest.Digest; |
| 79 | const context = yield* Effect.context<R>(); |
| 80 | const keyCache = yield* Cache.makeWith( |
| 81 | () => |
| 82 | options.loadOrCreateKey.pipe( |
| 83 | Effect.flatMap((key) => |
| 84 | thumbprint(key.publicJwk).pipe(Effect.map((value) => ({ key, thumbprint: value }))), |
| 85 | ), |
| 86 | Effect.provideService(Digest.Digest, digest), |
| 87 | Effect.provideContext(context), |
| 88 | ), |
| 89 | { |
| 90 | capacity: 1, |
| 91 | timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), |
| 92 | }, |
| 93 | ); |
| 94 | const loadKey = Cache.get(keyCache, undefined); |
| 95 | return ManagedRelayDpopSigner.of({ |
| 96 | thumbprint: loadKey.pipe( |
| 97 | Effect.map((loaded) => loaded.thumbprint), |
| 98 | Effect.mapError( |
| 99 | (cause) => new ManagedRelayDpopKeyLoadError({ keyStore: options.keyStore, cause }), |
| 100 | ), |
| 101 | Effect.withSpan("managedRelayDpopSigner.loadThumbprint"), |
| 102 | ), |
| 103 | createProof: Effect.fn("managedRelayDpopSigner.createProof")(function* (input) { |
| 104 | const creationError = (cause: unknown) => |
| 105 | new ManagedRelayDpopProofCreationError({ method: input.method, url: input.url, cause }); |
| 106 | const loaded = yield* loadKey.pipe(Effect.mapError(creationError)); |
| 107 | return yield* createProof({ ...input, key: loaded.key }).pipe( |
| 108 | Effect.provideService(SecureRandom.SecureRandom, random), |
| 109 | Effect.provideService(Digest.Digest, digest), |
| 110 | Effect.mapError(creationError), |
| 111 | ); |
| 112 | }), |
| 113 | }); |
| 114 | }), |
| 115 | ); |