@devries-cameron20 / t3code-1 / commits / a07be97ab0
Fork 0

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

refactor(client-runtime): share DPoP proof creation across web and mobile (#30540)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 4, 2026 at 10:35 UTC a07be97ab0753b2b5b0caecebba69d7f872594fa
9 files changed +251 -437
apps/mobile/src/features/cloud/dpop.test.ts
+1 -90
@@ -6,9 +6,8 @@ import { vi } from "vite-plus/test";
6 import { describe, expect, it } from "@effect/vitest";
7 import * as Digest from "effect/crypto/Digest";
8 import * as Effect from "effect/Effect";
9 -import { verifyDpopProof } from "@t3tools/shared/dpop";
9
11 -import { createDpopProof, generateDpopProofKeyPair, loadOrCreateDpopProofKeyPair } from "./dpop";
10 +import { loadOrCreateDpopProofKeyPair } from "./dpop";
11 import * as Dpop from "./dpop";
12
13 vi.mock("expo-crypto", () => ({
@@ -40,28 +39,6 @@ vi.mock("expo-secure-store", () => ({
39 },
40 }));
41
43 -function proofIat(proof: string): number {
44 - const payload = proof.split(".")[1];
45 - if (!payload) {
46 - throw new Error("Missing DPoP payload.");
47 - }
48 - const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
49 - readonly iat: number;
50 - };
51 - return decoded.iat;
52 -}
53 -
54 -function proofHtu(proof: string): string {
55 - const payload = proof.split(".")[1];
56 - if (!payload) {
57 - throw new Error("Missing DPoP payload.");
58 - }
59 - const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
60 - readonly htu: string;
61 - };
62 - return decoded.htu;
63 -}
64 -
42 describe("mobile DPoP", () => {
43 it.effect("passes typed-array digest input through the Expo Crypto adapter", () =>
44 Effect.gen(function* () {
@@ -78,7 +55,6 @@ describe("mobile DPoP", () => {
55 const first = yield* loadOrCreateDpopProofKeyPair();
56 const second = yield* loadOrCreateDpopProofKeyPair();
57
81 - expect(second.thumbprint).toBe(first.thumbprint);
58 expect(second.privateJwk).toEqual(first.privateJwk);
59 }).pipe(Effect.provide(Dpop.layer)),
60 );
@@ -92,69 +68,4 @@ describe("mobile DPoP", () => {
68 expect(error.message).toBe("Stored DPoP proof key is invalid.");
69 }).pipe(Effect.provide(Dpop.layer)),
70 );
95 -
96 - it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>
97 - Effect.gen(function* () {
98 - const proofKey = yield* generateDpopProofKeyPair();
99 - const connect = yield* createDpopProof({
100 - method: "POST",
101 - url: "https://relay.example.test/v1/environments/env-1/connect",
102 - accessToken: "clerk-token",
103 - proofKey,
104 - });
105 - const bootstrap = yield* createDpopProof({
106 - method: "POST",
107 - url: "https://desktop.example.test/oauth/token",
108 - proofKey,
109 - });
110 -
111 - expect(connect.thumbprint).toBe(proofKey.thumbprint);
112 - expect(bootstrap.thumbprint).toBe(proofKey.thumbprint);
113 - expect(
114 - verifyDpopProof({
115 - proof: connect.proof,
116 - method: "POST",
117 - url: "https://relay.example.test/v1/environments/env-1/connect",
118 - expectedThumbprint: proofKey.thumbprint,
119 - expectedAccessToken: "clerk-token",
120 - nowEpochSeconds: proofIat(connect.proof),
121 - }),
122 - ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
123 - expect(
124 - verifyDpopProof({
125 - proof: bootstrap.proof,
126 - method: "POST",
127 - url: "https://desktop.example.test/oauth/token",
128 - expectedThumbprint: proofKey.thumbprint,
129 - nowEpochSeconds: proofIat(bootstrap.proof),
130 - }),
131 - ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });
132 - }).pipe(Effect.provide(Dpop.layer)),
133 - );
134 -
135 - it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>
136 - Effect.gen(function* () {
137 - const proofKey = yield* generateDpopProofKeyPair();
138 - const proof = yield* createDpopProof({
139 - method: "POST",
140 - url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",
141 - accessToken: "clerk-token",
142 - proofKey,
143 - });
144 -
145 - expect(proofHtu(proof.proof)).toBe(
146 - "https://relay.example.test/v1/environments/env-1/connect",
147 - );
148 - expect(
149 - verifyDpopProof({
150 - proof: proof.proof,
151 - method: "POST",
152 - url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",
153 - expectedThumbprint: proofKey.thumbprint,
154 - expectedAccessToken: "clerk-token",
155 - nowEpochSeconds: proofIat(proof.proof),
156 - }),
157 - ).toMatchObject({ ok: true });
158 - }).pipe(Effect.provide(Dpop.layer)),
159 - );
71 });
apps/mobile/src/features/cloud/dpop.ts
+23 -123
@@ -1,4 +1,3 @@
1 -import * as Clock from "effect/Clock";
1 import * as Digest from "effect/crypto/Digest";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 import * as Data from "effect/Data";
@@ -10,7 +9,8 @@ import * as Schema from "effect/Schema";
9 import * as ExpoCrypto from "expo-crypto";
10 import * as SecureStore from "expo-secure-store";
11 import { p256 } from "@noble/curves/nist";
13 -import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";
12 +import { DpopProof } from "@t3tools/client-runtime/relay";
13 +import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";
14 import * as Layer from "effect/Layer";
15
16 export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
@@ -31,27 +31,6 @@ const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);
31 const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
32 const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);
33
34 -const DpopJwtHeaderJson = Schema.fromJsonString(
35 - Schema.Struct({
36 - typ: Schema.Literal("dpop+jwt"),
37 - alg: Schema.Literal("ES256"),
38 - jwk: DpopPublicJwk,
39 - }),
40 -);
41 -
42 -const DpopJwtPayloadJson = Schema.fromJsonString(
43 - Schema.Struct({
44 - htm: Schema.String,
45 - htu: Schema.String,
46 - jti: Schema.String,
47 - iat: Schema.Int,
48 - ath: Schema.optionalKey(Schema.String),
49 - }),
50 -);
51 -
52 -const encodeDpopJwtHeaderJson = Schema.encodeEffect(DpopJwtHeaderJson);
53 -const encodeDpopJwtPayloadJson = Schema.encodeEffect(DpopJwtPayloadJson);
54 -
34 function toExpoDigestAlgorithm(algorithm: Digest.Algorithm): ExpoCrypto.CryptoDigestAlgorithm {
35 switch (algorithm.name) {
36 case "MD5":
@@ -91,7 +70,6 @@ type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
70 export interface DpopProofKeyPair {
71 readonly privateJwk: DpopPrivateJwk;
72 readonly publicJwk: DpopPublicJwk;
94 - readonly thumbprint: string;
73 }
74
75 const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
@@ -110,40 +88,6 @@ function sha256Digest(
88 );
89 }
90
113 -function base64UrlSha256(
114 - data: Uint8Array,
115 - message: string,
116 -): Effect.Effect<string, CloudDpopError, Digest.Digest> {
117 - return sha256Digest(data, message).pipe(Effect.map(Base64Url.encode));
118 -}
119 -
120 -function dpopThumbprintInput(jwk: DpopPublicJwk): string {
121 - return JSON.stringify({
122 - crv: jwk.crv,
123 - kty: jwk.kty,
124 - x: jwk.x,
125 - y: jwk.y,
126 - });
127 -}
128 -
129 -function computeDpopJwkThumbprintEffect(
130 - jwk: DpopPublicJwk,
131 -): Effect.Effect<string, CloudDpopError, Digest.Digest> {
132 - return base64UrlSha256(
133 - new TextEncoder().encode(dpopThumbprintInput(jwk)),
134 - "Could not hash the DPoP public key thumbprint.",
135 - );
136 -}
137 -
138 -function computeDpopAccessTokenHashEffect(
139 - accessToken: string,
140 -): Effect.Effect<string, CloudDpopError, Digest.Digest> {
141 - return base64UrlSha256(
142 - new TextEncoder().encode(accessToken),
143 - "Could not hash the DPoP access token.",
144 - );
145 -}
146 -
91 function secureRandomBytes(
92 byteCount: number,
93 message: string,
@@ -190,12 +134,7 @@ export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair
134 try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
135 catch: cloudDpopError("Generated DPoP public key is invalid."),
136 });
193 - const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);
194 - return {
195 - privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),
196 - publicJwk,
197 - thumbprint,
198 - };
137 + return { privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk), publicJwk };
138 },
139 );
140
@@ -226,11 +165,7 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
165 },
166 catch: cloudDpopError("Stored DPoP proof key is invalid."),
167 });
229 - const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
230 - return {
231 - ...restored,
232 - thumbprint,
233 - };
168 + return restored;
169 }
170 const generated = yield* generateDpopProofKeyPair();
171 const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
@@ -244,63 +179,28 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
179 },
180 );
181
247 -function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
248 - const normalized = normalizeDpopHtu(url);
249 - return normalized
250 - ? Effect.succeed(normalized)
251 - : Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
252 -}
253 -
254 -export const createDpopProof = Effect.fn("dpop.createDpopProof")(function* (input: {
255 - readonly method: string;
256 - readonly url: string;
257 - readonly accessToken?: string;
258 - readonly proofKey?: DpopProofKeyPair;
259 -}): Effect.fn.Return<
260 - { readonly proof: string; readonly thumbprint: string },
261 - CloudDpopError,
262 - SecureRandom.SecureRandom | Digest.Digest
263 -> {
264 - const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
182 +/** The installation's DPoP key, signing with @noble/curves over an Expo SHA-256 digest. */
183 +export 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 });
269 - const nowMs = yield* Clock.currentTimeMillis;
270 - const jti = yield* SecureRandom.SecureRandom.pipe(
271 - Effect.flatMap((random) => random.uuidV4()),
272 - Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
273 - );
274 - const htu = yield* normalizeHtu(input.url);
275 - const header = yield* encodeDpopJwtHeaderJson({
276 - typ: "dpop+jwt",
277 - alg: "ES256",
278 - jwk: keyPair.publicJwk,
279 - }).pipe(
280 - Effect.map(Base64Url.encode),
281 - Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
282 - );
283 - const ath = input.accessToken ? yield* computeDpopAccessTokenHashEffect(input.accessToken) : null;
284 - const payload = yield* encodeDpopJwtPayloadJson({
285 - htm: input.method.toUpperCase(),
286 - htu,
287 - jti,
288 - iat: Math.floor(nowMs / 1_000),
289 - ...(ath ? { ath } : {}),
290 - }).pipe(
291 - Effect.map(Base64Url.encode),
292 - Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
293 - );
294 - const signatureInputHash = yield* sha256Digest(
295 - new TextEncoder().encode(`${header}.${payload}`),
296 - "Could not hash DPoP signing input.",
297 - );
298 - const signature = yield* Effect.try({
299 - try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
300 - catch: cloudDpopError("Could not sign DPoP proof."),
301 - });
190 return {
303 - proof: `${header}.${payload}.${Base64Url.encode(signature)}`,
304 - thumbprint: keyPair.thumbprint,
305 - };
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 });
apps/mobile/src/features/cloud/managedRelayLayer.ts
+6 -65
@@ -1,73 +1,14 @@
1 -import { ManagedRelay } from "@t3tools/client-runtime/relay";
1 +import { DpopProof, ManagedRelay } from "@t3tools/client-runtime/relay";
2 import { RelayMobileClientId } from "@t3tools/contracts/relay";
3 -import * as Cache from "effect/Cache";
4 -import * as Digest from "effect/crypto/Digest";
5 -import * as SecureRandom from "effect/crypto/SecureRandom";
6 -import * as Duration from "effect/Duration";
7 -import * as Effect from "effect/Effect";
8 -import * as Exit from "effect/Exit";
3 import * as Layer from "effect/Layer";
4
11 -import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
5 +import { loadOrCreateProofKey } from "./dpop";
6 import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
7
14 -const layerRelayDpopSigner = Layer.effect(
15 - ManagedRelay.ManagedRelayDpopSigner,
16 - Effect.gen(function* () {
17 - const random = yield* SecureRandom.SecureRandom;
18 - const digest = yield* Digest.Digest;
19 - const proofKeyCache = yield* Cache.makeWith(
20 - () =>
21 - loadOrCreateDpopProofKeyPair().pipe(
22 - Effect.provideService(SecureRandom.SecureRandom, random),
23 - Effect.provideService(Digest.Digest, digest),
24 - ),
25 - {
26 - capacity: 1,
27 - timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
28 - },
29 - );
30 - const loadProofKey = Cache.get(proofKeyCache, undefined);
31 - return ManagedRelay.ManagedRelayDpopSigner.of({
32 - thumbprint: loadProofKey.pipe(
33 - Effect.map((proofKey) => proofKey.thumbprint),
34 - Effect.mapError(
35 - (error) =>
36 - new ManagedRelay.ManagedRelayDpopKeyLoadError({
37 - keyStore: "expo-secure-store",
38 - cause: error,
39 - }),
40 - ),
41 - Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),
42 - ),
43 - createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {
44 - const proofKey = yield* loadProofKey.pipe(
45 - Effect.mapError(
46 - (error) =>
47 - new ManagedRelay.ManagedRelayDpopProofCreationError({
48 - method: input.method,
49 - url: input.url,
50 - cause: error,
51 - }),
52 - ),
53 - );
54 - return yield* createDpopProof({ ...input, proofKey }).pipe(
55 - Effect.provideService(SecureRandom.SecureRandom, random),
56 - Effect.provideService(Digest.Digest, digest),
57 - Effect.map((proof) => proof.proof),
58 - Effect.mapError(
59 - (error) =>
60 - new ManagedRelay.ManagedRelayDpopProofCreationError({
61 - method: input.method,
62 - url: input.url,
63 - cause: error,
64 - }),
65 - ),
66 - );
67 - }),
68 - });
69 - }),
70 -);
8 +const layerRelayDpopSigner = DpopProof.layerSigner({
9 + keyStore: "expo-secure-store",
10 + loadOrCreateKey: loadOrCreateProofKey(),
11 +});
12
13 export const layer = (relayUrl: string) =>
14 ManagedRelay.layer({
apps/web/src/cloud/dpop.test.ts deleted
-35
@@ -1,35 +0,0 @@
1 -import { verifyDpopProof } from "@t3tools/shared/dpop";
2 -import { describe, expect, it } from "@effect/vitest";
3 -import * as Effect from "effect/Effect";
4 -import * as TestClock from "effect/testing/TestClock";
5 -import { vi } from "vite-plus/test";
6 -
7 -import { createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
8 -import * as Dpop from "./dpop";
9 -
10 -describe("browser DPoP proofs", () => {
11 - it.effect("signs relay resource proofs with an access-token hash", () =>
12 - Effect.gen(function* () {
13 - vi.stubGlobal("indexedDB", undefined);
14 - yield* TestClock.setTime(1_700_000_000_000);
15 - const proofKey = yield* generateBrowserDpopKey;
16 - const proof = yield* createBrowserDpopProof({
17 - method: "POST",
18 - url: "https://relay.example.test/v1/environments/env-1/connect?ignored=true",
19 - accessToken: "relay-access-token",
20 - proofKey,
21 - }).pipe(Effect.provide(Dpop.layer));
22 -
23 - expect(
24 - verifyDpopProof({
25 - proof: proof.proof,
26 - method: "POST",
27 - url: "https://relay.example.test/v1/environments/env-1/connect",
28 - expectedThumbprint: proof.thumbprint,
29 - expectedAccessToken: "relay-access-token",
30 - nowEpochSeconds: 1_700_000_000,
31 - }),
32 - ).toMatchObject({ ok: true });
33 - }),
34 - );
35 -});
apps/web/src/cloud/dpop.ts
+25 -48
@@ -1,17 +1,11 @@
1 -import {
2 - computeDpopAccessTokenHash,
3 - computeDpopJwkThumbprint,
4 - DpopPublicJwk,
5 -} from "@t3tools/shared/dpop";
1 +import { DpopProof } from "@t3tools/client-runtime/relay";
2 +import { computeDpopJwkThumbprint, DpopPublicJwk } from "@t3tools/shared/dpop";
3 import * as Digest from "effect/crypto/Digest";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
5 import * as Signature from "effect/crypto/Signature";
9 -import * as Clock from "effect/Clock";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
12 -import * as Jwt from "effect/jose/Jwt";
8 import * as Layer from "effect/Layer";
14 -import * as Redacted from "effect/Redacted";
9 import * as Schema from "effect/Schema";
10
11 export interface BrowserDpopKey {
@@ -56,7 +50,7 @@ function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {
50 });
51 }
52
59 -export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null, BrowserDpopError> {
53 +function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null, BrowserDpopError> {
54 if (typeof indexedDB === "undefined") {
55 return Effect.succeed(null);
56 }
@@ -79,9 +73,7 @@ export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null,
73 );
74 }
75
82 -export function writeStoredBrowserDpopKey(
83 - key: BrowserDpopKey,
84 -): Effect.Effect<void, BrowserDpopError> {
76 +function writeStoredBrowserDpopKey(key: BrowserDpopKey): Effect.Effect<void, BrowserDpopError> {
77 if (typeof indexedDB === "undefined") {
78 return Effect.void;
79 }
@@ -102,7 +94,7 @@ export function writeStoredBrowserDpopKey(
94 );
95 }
96
105 -export const generateBrowserDpopKey = Effect.gen(function* () {
97 +const generateBrowserDpopKey = Effect.gen(function* () {
98 const generated = yield* Effect.tryPromise({
99 try: () =>
100 crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
@@ -140,41 +132,26 @@ export const generateBrowserDpopKey = Effect.gen(function* () {
132 };
133 });
134
143 -export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(function* (input: {
144 - readonly method: string;
145 - readonly url: string;
146 - readonly accessToken?: string;
147 - readonly proofKey: BrowserDpopKey;
148 -}): Effect.fn.Return<
149 - { readonly proof: string; readonly thumbprint: string },
150 - BrowserDpopError,
151 - SecureRandom.SecureRandom | Signature.Signature
152 -> {
153 - const normalizedUrl = yield* Effect.try({
154 - try: () => new URL(input.url),
155 - catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
156 - });
157 - normalizedUrl.search = "";
158 - normalizedUrl.hash = "";
159 - const jti = yield* SecureRandom.SecureRandom.pipe(Effect.flatMap((random) => random.uuidV4()));
160 - const key = yield* Signature.privateKeyFromCryptoKey(
135 +/** The stored key, or a new one persisted on first use, as a DPoP proof key. */
136 +export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(function* () {
137 + const signature = yield* Signature.Signature;
138 + const stored = yield* readStoredBrowserDpopKey();
139 + const browserKey = stored ?? (yield* generateBrowserDpopKey);
140 + if (stored === null) yield* writeStoredBrowserDpopKey(browserKey);
141 + const privateKey = yield* Signature.privateKeyFromCryptoKey(
142 Signature.ecdsaP256,
162 - input.proofKey.privateKey,
143 + browserKey.privateKey,
144 ).pipe(Effect.mapError((cause) => dpopError("Could not load DPoP proof key.", cause)));
164 - const proof = yield* Jwt.sign(
165 - Schema.Json,
166 - {
167 - htm: input.method.toUpperCase(),
168 - htu: normalizedUrl.toString(),
169 - jti,
170 - iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
171 - ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
172 - },
173 - { _tag: "PrivateKey", algorithm: "ES256", kid: undefined, key },
174 - { typ: "dpop+jwt", jwk: input.proofKey.publicJwk },
175 - ).pipe(
176 - Effect.map(Redacted.value),
177 - Effect.mapError((cause) => dpopError("Could not sign DPoP proof.", cause)),
178 - );
179 - return { proof, thumbprint: input.proofKey.thumbprint };
145 + return {
146 + publicJwk: browserKey.publicJwk,
147 + sign: (signingInput) =>
148 + signature
149 + .sign(privateKey, signingInput)
150 + .pipe(
151 + Effect.mapError(
152 + (cause) =>
153 + new DpopProof.DpopProofError({ message: "Could not sign DPoP proof.", cause }),
154 + ),
155 + ),
156 + } satisfies DpopProof.DpopProofKey;
157 });
apps/web/src/cloud/managedRelayLayer.ts
+6 -76
@@ -1,83 +1,13 @@
1 -import { ManagedRelay } from "@t3tools/client-runtime/relay";
1 +import { DpopProof, ManagedRelay } from "@t3tools/client-runtime/relay";
2 import { RelayWebClientId } from "@t3tools/contracts/relay";
3 -import * as SecureRandom from "effect/crypto/SecureRandom";
4 -import * as Signature from "effect/crypto/Signature";
5 -import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
7 -import * as Semaphore from "effect/Semaphore";
4
9 -import {
10 - createBrowserDpopProof,
11 - generateBrowserDpopKey,
12 - readStoredBrowserDpopKey,
13 - writeStoredBrowserDpopKey,
14 - type BrowserDpopKey,
15 -} from "./dpop";
5 +import { loadOrCreateProofKey } from "./dpop";
6
17 -const layerRelayDpopSigner = Layer.effect(
18 - ManagedRelay.ManagedRelayDpopSigner,
19 - Effect.gen(function* () {
20 - const random = yield* SecureRandom.SecureRandom;
21 - const signature = yield* Signature.Signature;
22 - const keyLoadSemaphore = yield* Semaphore.make(1);
23 - let loadedKey: BrowserDpopKey | null = null;
24 - const loadOrCreateBrowserDpopKey = keyLoadSemaphore.withPermit(
25 - Effect.gen(function* () {
26 - if (loadedKey) {
27 - return loadedKey;
28 - }
29 - const stored = yield* readStoredBrowserDpopKey();
30 - if (stored) {
31 - loadedKey = stored;
32 - return stored;
33 - }
34 - const generated = yield* generateBrowserDpopKey;
35 - yield* writeStoredBrowserDpopKey(generated);
36 - loadedKey = generated;
37 - return generated;
38 - }),
39 - );
40 -
41 - return ManagedRelay.ManagedRelayDpopSigner.of({
42 - thumbprint: loadOrCreateBrowserDpopKey.pipe(
43 - Effect.map((proofKey) => proofKey.thumbprint),
44 - Effect.mapError(
45 - (error) =>
46 - new ManagedRelay.ManagedRelayDpopKeyLoadError({
47 - keyStore: "indexed-db",
48 - cause: error,
49 - }),
50 - ),
51 - Effect.withSpan("web.managedRelayDpopSigner.loadThumbprint"),
52 - ),
53 - createProof: Effect.fn("web.managedRelayDpopSigner.createProof")(function* (input) {
54 - const proofKey = yield* loadOrCreateBrowserDpopKey.pipe(
55 - Effect.mapError(
56 - (error) =>
57 - new ManagedRelay.ManagedRelayDpopProofCreationError({
58 - method: input.method,
59 - url: input.url,
60 - cause: error,
61 - }),
62 - ),
63 - );
64 - return yield* createBrowserDpopProof({ ...input, proofKey }).pipe(
65 - Effect.provideService(SecureRandom.SecureRandom, random),
66 - Effect.provideService(Signature.Signature, signature),
67 - Effect.map((proof) => proof.proof),
68 - Effect.mapError(
69 - (error) =>
70 - new ManagedRelay.ManagedRelayDpopProofCreationError({
71 - method: input.method,
72 - url: input.url,
73 - cause: error,
74 - }),
75 - ),
76 - );
77 - }),
78 - });
79 - }),
80 -);
7 +const layerRelayDpopSigner = DpopProof.layerSigner({
8 + keyStore: "indexed-db",
9 + loadOrCreateKey: loadOrCreateProofKey(),
10 +});
11
12 export const layer = (relayUrl: string) =>
13 ManagedRelay.layer({ relayUrl, clientId: RelayWebClientId }).pipe(
packages/client-runtime/src/relay/dpopProof.test.ts new
+78
@@ -0,0 +1,78 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import { DpopPublicJwk, verifyDpopProof } from "@t3tools/shared/dpop";
3 +import * as Digest from "effect/crypto/Digest";
4 +import * as SecureRandom from "effect/crypto/SecureRandom";
5 +import * as Signature from "effect/crypto/Signature";
6 +import * as Effect from "effect/Effect";
7 +import * as Layer from "effect/Layer";
8 +import * as Schema from "effect/Schema";
9 +import * as TestClock from "effect/testing/TestClock";
10 +
11 +import * as DpopProof from "./dpopProof.ts";
12 +
13 +const decodePublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);
14 +
15 +const layer = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
16 + Layer.provideMerge(SecureRandom.layerWebCrypto),
17 +);
18 +
19 +// Mirrors the web adapter: a non-extractable WebCrypto key signed through Signature.
20 +const webCryptoProofKey = Effect.gen(function* () {
21 + const signature = yield* Signature.Signature;
22 + const pair = yield* Effect.promise(
23 + () =>
24 + crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, [
25 + "sign",
26 + "verify",
27 + ]) as Promise<CryptoKeyPair>,
28 + );
29 + const publicJwk = yield* Effect.promise(() =>
30 + crypto.subtle.exportKey("jwk", pair.publicKey),
31 + ).pipe(Effect.flatMap(decodePublicJwk), Effect.orDie);
32 + const privateKey = yield* Signature.privateKeyFromCryptoKey(
33 + Signature.ecdsaP256,
34 + pair.privateKey,
35 + ).pipe(Effect.orDie);
36 + return {
37 + publicJwk,
38 + sign: (data) => signature.sign(privateKey, data).pipe(Effect.orDie),
39 + } satisfies DpopProof.DpopProofKey;
40 +});
41 +
42 +describe("DpopProof", () => {
43 + it.effect("creates proofs the relay verifier accepts, with htu normalized and ath bound", () =>
44 + Effect.gen(function* () {
45 + yield* TestClock.setTime(1_700_000_000_000);
46 + const key = yield* webCryptoProofKey;
47 + const thumbprint = yield* DpopProof.thumbprint(key.publicJwk);
48 + const url = "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored";
49 + const proof = yield* DpopProof.createProof({
50 + method: "post",
51 + url,
52 + accessToken: "relay-access-token",
53 + key,
54 + });
55 +
56 + expect(
57 + verifyDpopProof({
58 + proof,
59 + method: "POST",
60 + url,
61 + expectedThumbprint: thumbprint,
62 + expectedAccessToken: "relay-access-token",
63 + nowEpochSeconds: 1_700_000_000,
64 + }),
65 + ).toMatchObject({ ok: true, thumbprint });
66 + }).pipe(Effect.provide(layer)),
67 + );
68 +
69 + it.effect("rejects an unparseable URL before signing", () =>
70 + Effect.gen(function* () {
71 + const key = yield* webCryptoProofKey;
72 + const error = yield* Effect.flip(
73 + DpopProof.createProof({ method: "GET", url: "not a url", key }),
74 + );
75 + expect(error.message).toBe("DPoP URL is invalid.");
76 + }).pipe(Effect.provide(layer)),
77 + );
78 +});
packages/client-runtime/src/relay/dpopProof.ts new
+111
@@ -0,0 +1,111 @@
1 +// RFC 9449 DPoP proofs for relay requests. Platforms supply the key: web keeps a
2 +// non-extractable WebCrypto key, mobile signs with @noble/curves (Hermes has no SubtleCrypto).
3 +import { normalizeDpopHtu, type DpopPublicJwk } from "@t3tools/shared/dpopCommon";
4 +import * as Cache from "effect/Cache";
5 +import * as Clock from "effect/Clock";
6 +import * as Digest from "effect/crypto/Digest";
7 +import * as SecureRandom from "effect/crypto/SecureRandom";
8 +import * as Data from "effect/Data";
9 +import * as Duration from "effect/Duration";
10 +import * as Effect from "effect/Effect";
11 +import * as Base64Url from "effect/encoding/Base64Url";
12 +import * as Exit from "effect/Exit";
13 +import * as Layer from "effect/Layer";
14 +
15 +import {
16 + ManagedRelayDpopKeyLoadError,
17 + ManagedRelayDpopProofCreationError,
18 + ManagedRelayDpopSigner,
19 +} from "./managedRelay.ts";
20 +
21 +export class DpopProofError extends Data.TaggedError("DpopProofError")<{
22 + readonly message: string;
23 + readonly cause?: unknown;
24 +}> {}
25 +
26 +/** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */
27 +export interface DpopProofKey {
28 + readonly publicJwk: DpopPublicJwk;
29 + readonly sign: (signingInput: Uint8Array) => Effect.Effect<Uint8Array, DpopProofError>;
30 +}
31 +
32 +const utf8 = (value: string) => new TextEncoder().encode(value);
33 +const encodeSegment = (value: unknown) => Base64Url.encode(utf8(JSON.stringify(value)));
34 +
35 +const sha256Base64Url = (data: Uint8Array) =>
36 + Effect.flatMap(Digest.Digest, (digest) => digest.digest(Digest.sha256, data)).pipe(
37 + Effect.map(Base64Url.encode),
38 + );
39 +
40 +/** RFC 7638 thumbprint: SHA-256 over the required members in lexicographic order. */
41 +export const thumbprint = (jwk: DpopPublicJwk) =>
42 + sha256Base64Url(utf8(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })));
43 +
44 +export const createProof = Effect.fn("DpopProof.createProof")(function* (input: {
45 + readonly method: string;
46 + readonly url: string;
47 + readonly accessToken?: string | undefined;
48 + readonly key: DpopProofKey;
49 +}) {
50 + const htu = normalizeDpopHtu(input.url);
51 + if (htu === null) return yield* new DpopProofError({ message: "DPoP URL is invalid." });
52 + const random = yield* SecureRandom.SecureRandom;
53 + const header = encodeSegment({ typ: "dpop+jwt", alg: "ES256", jwk: input.key.publicJwk });
54 + const payload = encodeSegment({
55 + htm: input.method.toUpperCase(),
56 + htu,
57 + jti: yield* random.uuidV4(),
58 + iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
59 + ...(input.accessToken ? { ath: yield* sha256Base64Url(utf8(input.accessToken)) } : {}),
60 + });
61 + const signature = yield* input.key.sign(utf8(`${header}.${payload}`));
62 + return `${header}.${payload}.${Base64Url.encode(signature)}`;
63 +});
64 +
65 +/** A relay DPoP signer that loads its key once and keeps it; a failed load is retried. */
66 +export const layerSigner = <E, R>(options: {
67 + readonly keyStore: ManagedRelayDpopKeyLoadError["keyStore"];
68 + readonly loadOrCreateKey: Effect.Effect<DpopProofKey, E, R>;
69 +}) =>
70 + Layer.effect(
71 + ManagedRelayDpopSigner,
72 + Effect.gen(function* () {
73 + const random = yield* SecureRandom.SecureRandom;
74 + const digest = yield* Digest.Digest;
75 + const context = yield* Effect.context<R>();
76 + const keyCache = yield* Cache.makeWith(
77 + () =>
78 + options.loadOrCreateKey.pipe(
79 + Effect.flatMap((key) =>
80 + thumbprint(key.publicJwk).pipe(Effect.map((value) => ({ key, thumbprint: value }))),
81 + ),
82 + Effect.provideService(Digest.Digest, digest),
83 + Effect.provideContext(context),
84 + ),
85 + {
86 + capacity: 1,
87 + timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
88 + },
89 + );
90 + const loadKey = Cache.get(keyCache, undefined);
91 + return ManagedRelayDpopSigner.of({
92 + thumbprint: loadKey.pipe(
93 + Effect.map((loaded) => loaded.thumbprint),
94 + Effect.mapError(
95 + (cause) => new ManagedRelayDpopKeyLoadError({ keyStore: options.keyStore, cause }),
96 + ),
97 + Effect.withSpan("managedRelayDpopSigner.loadThumbprint"),
98 + ),
99 + createProof: Effect.fn("managedRelayDpopSigner.createProof")(function* (input) {
100 + const creationError = (cause: unknown) =>
101 + new ManagedRelayDpopProofCreationError({ method: input.method, url: input.url, cause });
102 + const loaded = yield* loadKey.pipe(Effect.mapError(creationError));
103 + return yield* createProof({ ...input, key: loaded.key }).pipe(
104 + Effect.provideService(SecureRandom.SecureRandom, random),
105 + Effect.provideService(Digest.Digest, digest),
106 + Effect.mapError(creationError),
107 + );
108 + }),
109 + });
110 + }),
111 + );
packages/client-runtime/src/relay/index.ts
+1
@@ -1,4 +1,5 @@
1 export * as Discovery from "./discovery.ts";
2 +export * as DpopProof from "./dpopProof.ts";
3 export * from "./cloudAccountService.ts";
4 export * from "./errorPresentation.ts";
5 export * as ManagedRelay from "./managedRelay.ts";