Skip to content

Commit a07be97

Browse files
refactor(client-runtime): share DPoP proof creation across web and mobile (#30540)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 33ba7bf commit a07be97

9 files changed

Lines changed: 251 additions & 437 deletions

File tree

‎apps/mobile/src/features/cloud/dpop.test.ts‎

Lines changed: 1 addition & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@ import { vi } from "vite-plus/test";
66
import { describe, expect, it } from "@effect/vitest";
77
import * as Digest from "effect/crypto/Digest";
88
import * as Effect from "effect/Effect";
9-
import { verifyDpopProof } from "@t3tools/shared/dpop";
109

11-
import { createDpopProof, generateDpopProofKeyPair, loadOrCreateDpopProofKeyPair } from "./dpop";
10+
import { loadOrCreateDpopProofKeyPair } from "./dpop";
1211
import * as Dpop from "./dpop";
1312

1413
vi.mock("expo-crypto", () => ({
@@ -40,28 +39,6 @@ vi.mock("expo-secure-store", () => ({
4039
},
4140
}));
4241

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-
6542
describe("mobile DPoP", () => {
6643
it.effect("passes typed-array digest input through the Expo Crypto adapter", () =>
6744
Effect.gen(function* () {
@@ -78,7 +55,6 @@ describe("mobile DPoP", () => {
7855
const first = yield* loadOrCreateDpopProofKeyPair();
7956
const second = yield* loadOrCreateDpopProofKeyPair();
8057

81-
expect(second.thumbprint).toBe(first.thumbprint);
8258
expect(second.privateJwk).toEqual(first.privateJwk);
8359
}).pipe(Effect.provide(Dpop.layer)),
8460
);
@@ -92,69 +68,4 @@ describe("mobile DPoP", () => {
9268
expect(error.message).toBe("Stored DPoP proof key is invalid.");
9369
}).pipe(Effect.provide(Dpop.layer)),
9470
);
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-
);
16071
});

‎apps/mobile/src/features/cloud/dpop.ts‎

Lines changed: 23 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as Clock from "effect/Clock";
21
import * as Digest from "effect/crypto/Digest";
32
import * as SecureRandom from "effect/crypto/SecureRandom";
43
import * as Data from "effect/Data";
@@ -10,7 +9,8 @@ import * as Schema from "effect/Schema";
109
import * as ExpoCrypto from "expo-crypto";
1110
import * as SecureStore from "expo-secure-store";
1211
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";
1414
import * as Layer from "effect/Layer";
1515

1616
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
@@ -31,27 +31,6 @@ const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);
3131
const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
3232
const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);
3333

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-
5534
function toExpoDigestAlgorithm(algorithm: Digest.Algorithm): ExpoCrypto.CryptoDigestAlgorithm {
5635
switch (algorithm.name) {
5736
case "MD5":
@@ -91,7 +70,6 @@ type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;
9170
export interface DpopProofKeyPair {
9271
readonly privateJwk: DpopPrivateJwk;
9372
readonly publicJwk: DpopPublicJwk;
94-
readonly thumbprint: string;
9573
}
9674

9775
const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
@@ -110,40 +88,6 @@ function sha256Digest(
11088
);
11189
}
11290

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-
14791
function secureRandomBytes(
14892
byteCount: number,
14993
message: string,
@@ -190,12 +134,7 @@ export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair
190134
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
191135
catch: cloudDpopError("Generated DPoP public key is invalid."),
192136
});
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 };
199138
},
200139
);
201140

@@ -226,11 +165,7 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
226165
},
227166
catch: cloudDpopError("Stored DPoP proof key is invalid."),
228167
});
229-
const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);
230-
return {
231-
...restored,
232-
thumbprint,
233-
};
168+
return restored;
234169
}
235170
const generated = yield* generateDpopProofKeyPair();
236171
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
@@ -244,63 +179,28 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
244179
},
245180
);
246181

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();
265186
const privateKey = yield* Effect.try({
266187
try: () => base64UrlToBytes(keyPair.privateJwk.d),
267188
catch: cloudDpopError("Could not import DPoP private key."),
268189
});
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-
});
302190
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;
306206
});

‎apps/mobile/src/features/cloud/managedRelayLayer.ts‎

Lines changed: 6 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,14 @@
1-
import { ManagedRelay } from "@t3tools/client-runtime/relay";
1+
import { DpopProof, ManagedRelay } from "@t3tools/client-runtime/relay";
22
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";
93
import * as Layer from "effect/Layer";
104

11-
import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";
5+
import { loadOrCreateProofKey } from "./dpop";
126
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
137

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+
});
7112

7213
export const layer = (relayUrl: string) =>
7314
ManagedRelay.layer({

0 commit comments

Comments
 (0)