The best way to control Claude Code, Codex and more from any computer or phone
perf(mobile): sign DPoP proofs natively, up to 355x faster on Android (#31998)
Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Cameron Chisholm committed
Nov 9, 2026 at 06:13 UTC
445efb6dfcfc634f20367f5f79701bbac5dc24e5
14 files changed
+411
-68
apps/mobile/modules/t3-native-controls/android/build.gradle
+7
@@ -29,4 +29,11 @@ dependencies {
29
implementation 'androidx.activity:activity:1.8.2'
30
implementation 'androidx.compose.material3:material3-android:1.5.0-alpha17'
31
implementation 'androidx.window:window:1.5.1'
32
+ testImplementation 'junit:junit:4.13.2'
33
+}
34
+
35
+tasks.withType(Test).configureEach {
36
+ javaLauncher = javaToolchains.launcherFor {
37
+ languageVersion = JavaLanguageVersion.of(21)
38
+ }
39
}
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3DpopKeys.kt
new
+112
@@ -0,0 +1,112 @@
1
+package expo.modules.t3nativecontrols
2
+
3
+import java.math.BigInteger
4
+import java.security.KeyFactory
5
+import java.security.KeyPairGenerator
6
+import java.security.PrivateKey
7
+import java.security.PublicKey
8
+import java.security.Signature
9
+import java.security.interfaces.ECPrivateKey
10
+import java.security.interfaces.ECPublicKey
11
+import java.security.spec.ECGenParameterSpec
12
+import java.security.spec.ECParameterSpec
13
+import java.security.spec.ECPoint
14
+import java.security.spec.ECPrivateKeySpec
15
+import java.security.spec.ECPublicKeySpec
16
+
17
+/** P-256 keys for DPoP proofs, as 32-byte private scalars and 65-byte uncompressed public points. */
18
+internal object T3DpopKeys {
19
+ private const val SCALAR_BYTES = 32
20
+ private const val CURVE = "secp256r1"
21
+ private const val ALGORITHM = "SHA256withECDSA"
22
+
23
+ // AlgorithmParameters("EC") needs API 26; a generated key carries the same spec on any level.
24
+ private val curve: ECParameterSpec by lazy { (newKeyPair().public as ECPublicKey).params }
25
+
26
+ private fun newKeyPair() = KeyPairGenerator.getInstance("EC").run {
27
+ initialize(ECGenParameterSpec(CURVE))
28
+ generateKeyPair()
29
+ }
30
+
31
+ /** The private scalar followed by the public point. */
32
+ fun generate(): ByteArray {
33
+ val pair = newKeyPair()
34
+ val point = (pair.public as ECPublicKey).w
35
+ return scalar((pair.private as ECPrivateKey).s) +
36
+ byteArrayOf(UNCOMPRESSED) +
37
+ scalar(point.affineX) +
38
+ scalar(point.affineY)
39
+ }
40
+
41
+ // JCA cannot derive a public point, so prove the pair by signing and verifying.
42
+ fun matches(privateKey: ByteArray, publicKey: ByteArray): Boolean {
43
+ val probe = "t3code dpop key check".toByteArray()
44
+ val signature = Signature.getInstance(ALGORITHM).run {
45
+ initSign(privateKey(privateKey))
46
+ update(probe)
47
+ sign()
48
+ }
49
+ return Signature.getInstance(ALGORITHM).run {
50
+ initVerify(publicKey(publicKey))
51
+ update(probe)
52
+ verify(signature)
53
+ }
54
+ }
55
+
56
+ /** ES256 over the JWS signing input, as the raw `r‖s` pair JWS uses. */
57
+ fun sign(privateKey: ByteArray, signingInput: ByteArray): ByteArray {
58
+ val der = Signature.getInstance(ALGORITHM).run {
59
+ initSign(privateKey(privateKey))
60
+ update(signingInput)
61
+ sign()
62
+ }
63
+ return rawSignature(der)
64
+ }
65
+
66
+ /** Converts JCA's DER `SEQUENCE { INTEGER r, INTEGER s }` to fixed-width `r‖s`. */
67
+ internal fun rawSignature(der: ByteArray): ByteArray {
68
+ var offset = 0
69
+ fun expect(tag: Int) = require(der[offset++].toInt() == tag) { "Malformed ECDSA signature." }
70
+ fun length(): Int {
71
+ val first = der[offset++].toInt() and 0xff
72
+ if (first < 0x80) return first
73
+ var length = 0
74
+ repeat(first and 0x7f) { length = (length shl 8) or (der[offset++].toInt() and 0xff) }
75
+ return length
76
+ }
77
+ fun integer(): BigInteger {
78
+ expect(0x02)
79
+ val length = length()
80
+ return BigInteger(1, der.copyOfRange(offset, offset + length)).also { offset += length }
81
+ }
82
+ expect(0x30)
83
+ length()
84
+ return scalar(integer()) + scalar(integer())
85
+ }
86
+
87
+ private fun privateKey(bytes: ByteArray): PrivateKey {
88
+ require(bytes.size == SCALAR_BYTES) { "A DPoP private key is 32 bytes." }
89
+ return KeyFactory.getInstance("EC")
90
+ .generatePrivate(ECPrivateKeySpec(BigInteger(1, bytes), curve))
91
+ }
92
+
93
+ private fun publicKey(bytes: ByteArray): PublicKey {
94
+ require(bytes.size == 1 + 2 * SCALAR_BYTES && bytes[0] == UNCOMPRESSED) {
95
+ "A DPoP public key is an uncompressed P-256 point."
96
+ }
97
+ val x = BigInteger(1, bytes.copyOfRange(1, 1 + SCALAR_BYTES))
98
+ val y = BigInteger(1, bytes.copyOfRange(1 + SCALAR_BYTES, bytes.size))
99
+ return KeyFactory.getInstance("EC").generatePublic(ECPublicKeySpec(ECPoint(x, y), curve))
100
+ }
101
+
102
+ /** Big-endian and left-padded to 32 bytes, without BigInteger's sign byte. */
103
+ private fun scalar(value: BigInteger): ByteArray {
104
+ val bytes = value.toByteArray()
105
+ return when {
106
+ bytes.size > SCALAR_BYTES -> bytes.copyOfRange(bytes.size - SCALAR_BYTES, bytes.size)
107
+ else -> ByteArray(SCALAR_BYTES - bytes.size) + bytes
108
+ }
109
+ }
110
+
111
+ private const val UNCOMPRESSED: Byte = 0x04
112
+}
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt
+8
@@ -39,6 +39,14 @@ class T3NativeControlsModule : Module() {
39
DateFormat.is24HourFormat(context)
40
}
41
42
+ AsyncFunction("generateDpopKey") { T3DpopKeys.generate() }
43
+
44
+ AsyncFunction("dpopKeyMatches") { privateKey: ByteArray, publicKey: ByteArray ->
45
+ T3DpopKeys.matches(privateKey, publicKey)
46
+ }
47
+
48
+ AsyncFunction("signDpop") { key: ByteArray, input: ByteArray -> T3DpopKeys.sign(key, input) }
49
+
50
AsyncFunction("openFile") { uri: String, mimeType: String, promise: Promise ->
51
check(filePreviewPromise == null) { "A document viewer is already open." }
52
val activity = appContext.currentActivity ?: error("The app is not active.")
apps/mobile/modules/t3-native-controls/android/src/test/java/expo/modules/t3nativecontrols/T3DpopKeysTest.kt
new
+66
@@ -0,0 +1,66 @@
1
+package expo.modules.t3nativecontrols
2
+
3
+import java.math.BigInteger
4
+import java.security.KeyFactory
5
+import java.security.Signature
6
+import java.security.spec.ECGenParameterSpec
7
+import java.security.spec.ECParameterSpec
8
+import java.security.spec.ECPoint
9
+import java.security.spec.ECPublicKeySpec
10
+import java.security.AlgorithmParameters
11
+import org.junit.Assert.assertArrayEquals
12
+import org.junit.Assert.assertEquals
13
+import org.junit.Assert.assertFalse
14
+import org.junit.Assert.assertTrue
15
+import org.junit.Test
16
+
17
+class T3DpopKeysTest {
18
+ @Test
19
+ fun signsRawSignaturesThatVerifyAgainstTheGeneratedPublicKey() {
20
+ val key = T3DpopKeys.generate()
21
+ val privateKey = key.copyOfRange(0, 32)
22
+ val publicKey = key.copyOfRange(32, 97)
23
+ assertTrue(T3DpopKeys.matches(privateKey, publicKey))
24
+ assertFalse(T3DpopKeys.matches(T3DpopKeys.generate().copyOfRange(0, 32), publicKey))
25
+
26
+ val input = "header.payload".toByteArray()
27
+ repeat(32) {
28
+ val raw = T3DpopKeys.sign(privateKey, input)
29
+ assertEquals(64, raw.size)
30
+ val verifier = Signature.getInstance("SHA256withECDSA").apply {
31
+ initVerify(jcaPublicKey(publicKey))
32
+ update(input)
33
+ }
34
+ assertTrue(verifier.verify(der(raw)))
35
+ }
36
+ }
37
+
38
+ @Test
39
+ fun convertsShortAndSignPaddedDerIntegersToFixedWidth() {
40
+ // r has a 0x00 sign byte (33 bytes); s is a single byte.
41
+ val r = byteArrayOf(0) + ByteArray(32) { 0x80.toByte() }
42
+ val der = byteArrayOf(0x30, (2 + r.size + 3).toByte(), 0x02, r.size.toByte()) + r +
43
+ byteArrayOf(0x02, 0x01, 0x05)
44
+ val expected = ByteArray(32) { 0x80.toByte() } + ByteArray(31) + byteArrayOf(5)
45
+ assertArrayEquals(expected, T3DpopKeys.rawSignature(der))
46
+ }
47
+
48
+ private fun jcaPublicKey(bytes: ByteArray) = KeyFactory.getInstance("EC").generatePublic(
49
+ ECPublicKeySpec(
50
+ ECPoint(BigInteger(1, bytes.copyOfRange(1, 33)), BigInteger(1, bytes.copyOfRange(33, 65))),
51
+ AlgorithmParameters.getInstance("EC").run {
52
+ init(ECGenParameterSpec("secp256r1"))
53
+ getParameterSpec(ECParameterSpec::class.java)
54
+ },
55
+ ),
56
+ )
57
+
58
+ private fun der(raw: ByteArray): ByteArray {
59
+ fun integer(bytes: ByteArray): ByteArray {
60
+ val value = BigInteger(1, bytes).toByteArray()
61
+ return byteArrayOf(0x02, value.size.toByte()) + value
62
+ }
63
+ val body = integer(raw.copyOfRange(0, 32)) + integer(raw.copyOfRange(32, 64))
64
+ return byteArrayOf(0x30, body.size.toByte()) + body
65
+ }
66
+}
apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift
new
+20
@@ -0,0 +1,20 @@
1
+import CryptoKit
2
+import Foundation
3
+
4
+/// P-256 keys for DPoP proofs, as 32-byte private scalars and 65-byte uncompressed public points.
5
+enum T3DpopKeys {
6
+ /// The private scalar followed by the public point.
7
+ static func generate() -> Data {
8
+ let key = P256.Signing.PrivateKey()
9
+ return key.rawRepresentation + key.publicKey.x963Representation
10
+ }
11
+
12
+ static func matches(privateKey: Data, publicKey: Data) throws -> Bool {
13
+ try P256.Signing.PrivateKey(rawRepresentation: privateKey).publicKey.x963Representation == publicKey
14
+ }
15
+
16
+ /// ES256 over the JWS signing input, as the raw `r‖s` pair JWS uses.
17
+ static func sign(privateKey: Data, signingInput: Data) throws -> Data {
18
+ try P256.Signing.PrivateKey(rawRepresentation: privateKey).signature(for: signingInput).rawRepresentation
19
+ }
20
+}
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+10
@@ -53,6 +53,16 @@ public final class T3NativeControlsModule: Module {
53
ViewName("ScrollEdgeBleed")
54
}
55
56
+ AsyncFunction("generateDpopKey") { T3DpopKeys.generate() }
57
+
58
+ AsyncFunction("dpopKeyMatches") { (privateKey: Data, publicKey: Data) in
59
+ try T3DpopKeys.matches(privateKey: privateKey, publicKey: publicKey)
60
+ }
61
+
62
+ AsyncFunction("signDpop") { (privateKey: Data, signingInput: Data) in
63
+ try T3DpopKeys.sign(privateKey: privateKey, signingInput: signingInput)
64
+ }
65
+
66
AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
67
try self.presentVideo(
68
url: url,
apps/mobile/package.json
-1
@@ -60,7 +60,6 @@
60
"@expo/ui": "58.0.20",
61
"@legendapp/list": "catalog:",
62
"@material/material-color-utilities": "0.3.0",
63
- "@noble/curves": "catalog:",
63
"@pierre/diffs": "catalog:",
64
"@pierre/highlights": "catalog:",
65
"@react-native-ai/apple": "0.12.0",
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+6
@@ -141,6 +141,12 @@ vi.mock("expo-crypto", () => ({
141
},
142
}));
143
144
+vi.mock("expo", async () => {
145
+ const { createNodeDpopKeysModule } = await import("../cloud/dpop.testing");
146
+ const dpopKeys = createNodeDpopKeysModule();
147
+ return { requireNativeModule: () => dpopKeys };
148
+});
149
+
150
vi.mock("expo-secure-store", () => ({
151
getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),
152
setItemAsync: (key: string, value: string) => {
apps/mobile/src/features/cloud/dpop.test.ts
+77
-1
@@ -4,10 +4,12 @@ import * as NodeCrypto from "node:crypto";
4
5
import { vi } from "vite-plus/test";
6
import { describe, expect, it } from "@effect/vitest";
7
+import { DpopProof } from "@t3tools/client-runtime/relay";
8
+import { verifyDpopProof } from "@t3tools/shared/dpop";
9
import * as Digest from "effect/crypto/Digest";
10
import * as Effect from "effect/Effect";
11
10
-import { loadOrCreateDpopProofKeyPair } from "./dpop";
12
+import { loadOrCreateDpopProofKeyPair, loadOrCreateProofKey } from "./dpop";
13
import * as Dpop from "./dpop";
14
15
vi.mock("expo-crypto", () => ({
@@ -39,6 +41,12 @@ vi.mock("expo-secure-store", () => ({
41
},
42
}));
43
44
+vi.mock("expo", async () => {
45
+ const { createNodeDpopKeysModule } = await import("./dpop.testing");
46
+ const dpopKeys = createNodeDpopKeysModule();
47
+ return { requireNativeModule: () => dpopKeys };
48
+});
49
+
50
describe("mobile DPoP", () => {
51
it.effect("passes typed-array digest input through the Expo Crypto adapter", () =>
52
Effect.gen(function* () {
@@ -68,4 +76,72 @@ describe("mobile DPoP", () => {
76
expect(error.message).toBe("Stored DPoP proof key is invalid.");
77
}).pipe(Effect.provide(Dpop.layer)),
78
);
79
+
80
+ it.effect("rejects a persisted key whose public half belongs to another key", () =>
81
+ Effect.gen(function* () {
82
+ secureStore.clear();
83
+ const { privateJwk } = yield* loadOrCreateDpopProofKeyPair();
84
+ secureStore.clear();
85
+ const other = yield* loadOrCreateDpopProofKeyPair();
86
+ secureStore.set(
87
+ "t3code.cloud.dpop-proof-key",
88
+ JSON.stringify({ ...privateJwk, x: other.publicJwk.x, y: other.publicJwk.y }),
89
+ );
90
+
91
+ const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
92
+
93
+ expect(error.message).toBe("Stored DPoP proof key is invalid.");
94
+ }),
95
+ );
96
+
97
+ // X ends in 0x00, so a zero-filled 31-byte X, or a 33-byte X whose extra byte Y overwrites,
98
+ // still names the same point.
99
+ const privateJwkWithZeroEndedX = {
100
+ kty: "EC",
101
+ crv: "P-256",
102
+ x: "TCE1CTXQ3-B54Fwv9yDlkE3rgcWsJsuGIv2Q9QHcZAA",
103
+ y: "zL4Eewo43mYmVjtqh597_dGnKa7lkxxB5XaQk32V9UM",
104
+ d: "mzWsJz_1-NerI3_NPtF_hcQhQrXnEITcNEmu5BzaDK4",
105
+ };
106
+ const xBytes = Buffer.from(privateJwkWithZeroEndedX.x, "base64url");
107
+ it.effect.each([
108
+ { length: "short", x: xBytes.subarray(0, 31) },
109
+ { length: "long", x: Buffer.concat([xBytes, Buffer.of(7)]) },
110
+ ])("rejects a persisted key with a $length coordinate", ({ x }) =>
111
+ Effect.gen(function* () {
112
+ secureStore.set(
113
+ "t3code.cloud.dpop-proof-key",
114
+ JSON.stringify({ ...privateJwkWithZeroEndedX, x: x.toString("base64url") }),
115
+ );
116
+
117
+ const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
118
+
119
+ expect(error.message).toBe("Stored DPoP proof key is invalid.");
120
+ }),
121
+ );
122
+
123
+ it.effect("signs proofs that the relay's verifier accepts", () =>
124
+ Effect.gen(function* () {
125
+ secureStore.clear();
126
+ const key = yield* loadOrCreateProofKey();
127
+ const url = "https://relay.t3.codes/v1/environments";
128
+ const proof = yield* DpopProof.createProof({
129
+ method: "GET",
130
+ url,
131
+ accessToken: "access-token",
132
+ key,
133
+ });
134
+
135
+ // The proof's `iat` comes from the TestClock, which starts at 0.
136
+ expect(
137
+ verifyDpopProof({
138
+ proof,
139
+ method: "GET",
140
+ url,
141
+ nowEpochSeconds: 0,
142
+ expectedAccessToken: "access-token",
143
+ }),
144
+ ).toMatchObject({ ok: true });
145
+ }).pipe(Effect.provide(Dpop.layer)),
146
+ );
147
});
apps/mobile/src/features/cloud/dpop.testing.ts
new
+48
@@ -0,0 +1,48 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+/// <reference types="node" />
3
+
4
+import * as NodeCrypto from "node:crypto";
5
+
6
+function publicKeyFor(privateKey: Uint8Array) {
7
+ const ecdh = NodeCrypto.createECDH("prime256v1");
8
+ ecdh.setPrivateKey(privateKey);
9
+ return ecdh.getPublicKey();
10
+}
11
+
12
+/**
13
+ * Stands in for the T3NativeControls DPoP functions with Node's P-256.
14
+ * Return it from a mocked `expo` `requireNativeModule`.
15
+ */
16
+export function createNodeDpopKeysModule() {
17
+ return {
18
+ generateDpopKey: () => {
19
+ const ecdh = NodeCrypto.createECDH("prime256v1");
20
+ const publicKey = ecdh.generateKeys();
21
+ const privateKey = ecdh.getPrivateKey();
22
+ return Promise.resolve(
23
+ new Uint8Array(
24
+ Buffer.concat([Buffer.alloc(32 - privateKey.length), privateKey, publicKey]),
25
+ ),
26
+ );
27
+ },
28
+ dpopKeyMatches: (privateKey: Uint8Array, publicKey: Uint8Array) =>
29
+ Promise.resolve(publicKeyFor(privateKey).equals(publicKey)),
30
+ signDpop: (privateKey: Uint8Array, signingInput: Uint8Array) => {
31
+ const publicKey = publicKeyFor(privateKey);
32
+ const key = NodeCrypto.createPrivateKey({
33
+ format: "jwk",
34
+ key: {
35
+ kty: "EC",
36
+ crv: "P-256",
37
+ d: Buffer.from(privateKey).toString("base64url"),
38
+ x: publicKey.subarray(1, 33).toString("base64url"),
39
+ y: publicKey.subarray(33).toString("base64url"),
40
+ },
41
+ });
42
+ // ieee-p1363 is the raw r‖s pair the native functions return.
43
+ return Promise.resolve(
44
+ new Uint8Array(NodeCrypto.sign("sha256", signingInput, { key, dsaEncoding: "ieee-p1363" })),
45
+ );
46
+ },
47
+ };
48
+}
apps/mobile/src/features/cloud/dpop.ts
+50
-62
@@ -7,7 +7,6 @@ import * as Result from "effect/Result";
7
import * as Schema from "effect/Schema";
8
import * as ExpoCrypto from "expo-crypto";
9
import * as SecureStore from "expo-secure-store";
10
-import { p256 } from "@noble/curves/nist";
10
import { DpopProof } from "@t3tools/client-runtime/relay";
11
import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";
12
import * as Layer from "effect/Layer";
@@ -75,28 +74,37 @@ export interface DpopProofKeyPair {
74
75
const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";
76
77
+interface NativeDpopKeys {
78
+ /** A 32-byte private scalar followed by its 65-byte uncompressed public point. */
79
+ generateDpopKey(): Promise<Uint8Array>;
80
+ dpopKeyMatches(privateKey: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
81
+ /** ES256 over the signing input, as the raw 64-byte `r‖s` pair. */
82
+ signDpop(privateKey: Uint8Array, signingInput: Uint8Array): Promise<Uint8Array>;
83
+}
84
+
85
+// Platform crypto: in Hermes, @noble/curves blocks JS for about a second on its first P-256 key.
86
+// Imported lazily: loading `expo` at module scope breaks Node tests that import this file.
87
+const nativeDpopKeys = async () =>
88
+ (await import("expo")).requireNativeModule<NativeDpopKeys>("T3NativeControls");
89
+
90
function base64UrlToBytes(value: string): Uint8Array {
91
return Result.getOrThrow(Base64Url.decode(value));
92
}
93
82
-function sha256Digest(
83
- data: Uint8Array,
84
- message: string,
85
-): Effect.Effect<Uint8Array, CloudDpopError, Digest.Digest> {
86
- return Digest.Digest.pipe(
87
- Effect.flatMap((service) => service.digest(Digest.sha256, data)),
88
- Effect.mapError(cloudDpopError(message)),
89
- );
94
+function coordinateBytes(value: string): Uint8Array {
95
+ const bytes = base64UrlToBytes(value);
96
+ if (bytes.length !== 32 || Base64Url.encode(bytes) !== value) {
97
+ throw new Error("DPoP key coordinate is not 32 canonical bytes.");
98
+ }
99
+ return bytes;
100
}
101
92
-function secureRandomBytes(
93
- byteCount: number,
94
- message: string,
95
-): Effect.Effect<Uint8Array, CloudDpopError, SecureRandom.SecureRandom> {
96
- return SecureRandom.SecureRandom.pipe(
97
- Effect.flatMap((random) => random.randomBytes(byteCount)),
98
- Effect.mapError(cloudDpopError(message)),
99
- );
102
+function uncompressedPublicKeyFromJwk(jwk: DpopPublicJwk): Uint8Array {
103
+ const publicKey = new Uint8Array(65);
104
+ publicKey[0] = 0x04;
105
+ publicKey.set(coordinateBytes(jwk.x), 1);
106
+ publicKey.set(coordinateBytes(jwk.y), 33);
107
+ return publicKey;
108
}
109
110
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
@@ -119,32 +127,21 @@ function privateJwkFromPrivateKey(
127
}
128
129
export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(
122
- function* (): Effect.fn.Return<
123
- DpopProofKeyPair,
124
- CloudDpopError,
125
- SecureRandom.SecureRandom | Digest.Digest
126
- > {
127
- let privateKey: Uint8Array;
128
- do {
129
- privateKey = yield* secureRandomBytes(
130
- p256.CURVE.nByteLength,
131
- "Could not generate DPoP key pair randomness.",
132
- );
133
- } while (!p256.utils.isValidPrivateKey(privateKey));
130
+ function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError> {
131
+ const key = yield* Effect.tryPromise({
132
+ try: async () => (await nativeDpopKeys()).generateDpopKey(),
133
+ catch: cloudDpopError("Could not generate the DPoP key pair."),
134
+ });
135
const publicJwk = yield* Effect.try({
135
- try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
136
+ try: () => publicJwkFromUncompressedPublicKey(key.slice(32)),
137
catch: cloudDpopError("Generated DPoP public key is invalid."),
138
});
138
- return { privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk), publicJwk };
139
+ return { privateJwk: privateJwkFromPrivateKey(key.slice(0, 32), publicJwk), publicJwk };
140
},
141
);
142
143
export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(
143
- function* (): Effect.fn.Return<
144
- DpopProofKeyPair,
145
- CloudDpopError,
146
- SecureRandom.SecureRandom | Digest.Digest
147
- > {
144
+ function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError> {
145
const stored = yield* Effect.tryPromise({
146
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
147
catch: cloudDpopError("Could not read the DPoP proof key."),
@@ -153,20 +150,19 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
150
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
151
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
152
);
156
- const restored = yield* Effect.try({
157
- try: () => {
158
- const privateKey = base64UrlToBytes(storedPrivateJwk.d);
159
- const publicJwk = publicJwkFromUncompressedPublicKey(
160
- p256.getPublicKey(privateKey, false),
161
- );
162
- if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
163
- throw new Error("Stored DPoP key does not match its public key.");
164
- }
165
- return { privateJwk: storedPrivateJwk, publicJwk };
166
- },
153
+ const { d, ...publicJwk } = storedPrivateJwk;
154
+ const matches = yield* Effect.tryPromise({
155
+ try: async () =>
156
+ (await nativeDpopKeys()).dpopKeyMatches(
157
+ base64UrlToBytes(d),
158
+ uncompressedPublicKeyFromJwk(publicJwk),
159
+ ),
160
catch: cloudDpopError("Stored DPoP proof key is invalid."),
161
});
169
- return restored;
162
+ if (!matches) {
163
+ return yield* new CloudDpopError({ message: "Stored DPoP proof key is invalid." });
164
+ }
165
+ return { privateJwk: storedPrivateJwk, publicJwk };
166
}
167
const generated = yield* generateDpopProofKeyPair();
168
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
@@ -180,9 +176,8 @@ export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProo
176
},
177
);
178
183
-/** The installation's DPoP key, signing with @noble/curves over an Expo SHA-256 digest. */
179
+/** The installation's DPoP key, signing with the platform's P-256. */
180
export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(function* () {
185
- const digest = yield* Digest.Digest;
181
const keyPair = yield* loadOrCreateDpopProofKeyPair();
182
const privateKey = yield* Effect.try({
183
try: () => base64UrlToBytes(keyPair.privateJwk.d),
@@ -191,17 +186,10 @@ export const loadOrCreateProofKey = Effect.fn("dpop.loadOrCreateProofKey")(funct
186
return {
187
publicJwk: keyPair.publicJwk,
188
sign: (signingInput) =>
194
- sha256Digest(signingInput, "Could not hash DPoP signing input.").pipe(
195
- Effect.provideService(Digest.Digest, digest),
196
- Effect.flatMap((hash) =>
197
- Effect.try({
198
- try: () => p256.sign(hash, privateKey, { prehash: false }).toCompactRawBytes(),
199
- catch: cloudDpopError("Could not sign DPoP proof."),
200
- }),
201
- ),
202
- Effect.mapError(
203
- (cause) => new DpopProof.DpopProofError({ message: "Could not sign DPoP proof.", cause }),
204
- ),
205
- ),
189
+ Effect.tryPromise({
190
+ try: async () => (await nativeDpopKeys()).signDpop(privateKey, signingInput),
191
+ catch: (cause) =>
192
+ new DpopProof.DpopProofError({ message: "Could not sign DPoP proof.", cause }),
193
+ }),
194
} satisfies DpopProof.DpopProofKey;
195
});
apps/mobile/src/features/cloud/managedRelayLayer.test.ts
+6
@@ -23,6 +23,12 @@ vi.mock("expo-crypto", () => ({
23
24
const secureStore = new Map<string, string>();
25
let failNextRead = false;
26
+vi.mock("expo", async () => {
27
+ const { createNodeDpopKeysModule } = await import("./dpop.testing");
28
+ const dpopKeys = createNodeDpopKeysModule();
29
+ return { requireNativeModule: () => dpopKeys };
30
+});
31
+
32
vi.mock("expo-secure-store", () => ({
33
getItemAsync: (key: string) => {
34
if (failNextRead) {
packages/client-runtime/src/relay/dpopProof.ts
+1
-1
@@ -1,5 +1,5 @@
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).
2
+// non-extractable WebCrypto key, mobile signs with the platform's P-256 through a native module.
3
import { normalizeDpopHtu, type DpopPublicJwk } from "@t3tools/shared/dpopCommon";
4
import * as Cache from "effect/Cache";
5
import * as Clock from "effect/Clock";
pnpm-lock.yaml
-3
@@ -553,9 +553,6 @@ importers:
553
'@material/material-color-utilities':
554
specifier: 0.3.0
555
version: 0.3.0
556
- '@noble/curves':
557
- specifier: 'catalog:'
558
- version: 1.9.1
556
'@pierre/diffs':
557
specifier: 1.6.1
558
version: 1.6.1(patch_hash=322ac5f5db8b5715189c010802047f8235c3a45d8ed5ca0ba60fac266e2eba34)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)