@circle-fin/daa-react-native-sdk 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/DaaReactNativeSdk.podspec +63 -0
  2. package/LICENSE +176 -0
  3. package/README.md +217 -2
  4. package/android/build.gradle +97 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
  7. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +121 -0
  8. package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
  9. package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
  10. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +73 -0
  11. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +185 -0
  12. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +73 -0
  13. package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
  14. package/build/DaaClient.d.ts +57 -0
  15. package/build/DaaClient.js +158 -0
  16. package/build/api/AccountLimitsClient.d.ts +79 -0
  17. package/build/api/AccountLimitsClient.js +142 -0
  18. package/build/api/AccountsClient.d.ts +95 -0
  19. package/build/api/AccountsClient.js +276 -0
  20. package/build/api/AchFiatAccountsClient.d.ts +92 -0
  21. package/build/api/AchFiatAccountsClient.js +142 -0
  22. package/build/api/AuthClient.d.ts +120 -0
  23. package/build/api/AuthClient.js +257 -0
  24. package/build/api/DaaUserClient.d.ts +124 -0
  25. package/build/api/DaaUserClient.js +245 -0
  26. package/build/api/DepositAddressesClient.d.ts +112 -0
  27. package/build/api/DepositAddressesClient.js +222 -0
  28. package/build/api/DepositsClient.d.ts +106 -0
  29. package/build/api/DepositsClient.js +183 -0
  30. package/build/api/FiatAccountsClient.d.ts +43 -0
  31. package/build/api/FiatAccountsClient.js +46 -0
  32. package/build/api/TransactionsClient.d.ts +64 -0
  33. package/build/api/TransactionsClient.js +120 -0
  34. package/build/api/TransfersClient.d.ts +104 -0
  35. package/build/api/TransfersClient.js +321 -0
  36. package/build/api/WireFiatAccountsClient.d.ts +99 -0
  37. package/build/api/WireFiatAccountsClient.js +156 -0
  38. package/build/api/WithdrawalsClient.d.ts +94 -0
  39. package/build/api/WithdrawalsClient.js +305 -0
  40. package/build/api/loginFailure.d.ts +43 -0
  41. package/build/api/loginFailure.js +64 -0
  42. package/build/api/pagination.d.ts +29 -0
  43. package/build/api/pagination.js +50 -0
  44. package/build/api/queryParameters.d.ts +23 -0
  45. package/build/api/queryParameters.js +77 -0
  46. package/build/api/resourceRequest.d.ts +60 -0
  47. package/build/api/resourceRequest.js +79 -0
  48. package/build/api/signedResource.d.ts +77 -0
  49. package/build/api/signedResource.js +168 -0
  50. package/build/auth/RegistrationFlowKey.d.ts +93 -0
  51. package/build/auth/RegistrationFlowKey.js +203 -0
  52. package/build/auth/daaRegistrationNative.d.ts +80 -0
  53. package/build/auth/daaRegistrationNative.js +184 -0
  54. package/build/auth/deviceAuthorization.d.ts +73 -0
  55. package/build/auth/deviceAuthorization.js +243 -0
  56. package/build/auth/ownerGrant.d.ts +29 -0
  57. package/build/auth/ownerGrant.js +90 -0
  58. package/build/auth/prepareReceipt.d.ts +150 -0
  59. package/build/auth/prepareReceipt.js +357 -0
  60. package/build/auth/registrationAuthorization.d.ts +48 -0
  61. package/build/auth/registrationAuthorization.js +243 -0
  62. package/build/auth/registrationCodeVerifier.d.ts +31 -0
  63. package/build/auth/registrationCodeVerifier.js +75 -0
  64. package/build/config.d.ts +79 -0
  65. package/build/config.js +116 -0
  66. package/build/crypto/base64url.d.ts +26 -0
  67. package/build/crypto/base64url.js +87 -0
  68. package/build/crypto/bytes.d.ts +27 -0
  69. package/build/crypto/bytes.js +32 -0
  70. package/build/crypto/es256Jws.d.ts +56 -0
  71. package/build/crypto/es256Jws.js +196 -0
  72. package/build/crypto/jwkThumbprint.d.ts +32 -0
  73. package/build/crypto/jwkThumbprint.js +49 -0
  74. package/build/crypto/random.d.ts +35 -0
  75. package/build/crypto/random.js +106 -0
  76. package/build/crypto/serialization.d.ts +26 -0
  77. package/build/crypto/serialization.js +43 -0
  78. package/build/crypto/sha256.d.ts +18 -0
  79. package/build/crypto/sha256.js +100 -0
  80. package/build/errors.d.ts +190 -0
  81. package/build/errors.js +252 -0
  82. package/build/index.d.ts +61 -0
  83. package/build/index.js +67 -0
  84. package/build/models/Account.d.ts +201 -0
  85. package/build/models/Account.js +147 -0
  86. package/build/models/AccountLimitsUsage.d.ts +169 -0
  87. package/build/models/AccountLimitsUsage.js +86 -0
  88. package/build/models/Ach.d.ts +135 -0
  89. package/build/models/Ach.js +184 -0
  90. package/build/models/AddressObject.d.ts +128 -0
  91. package/build/models/AddressObject.js +141 -0
  92. package/build/models/BusinessPii.d.ts +84 -0
  93. package/build/models/BusinessPii.js +142 -0
  94. package/build/models/CreateAccountRequest.d.ts +74 -0
  95. package/build/models/CreateAccountRequest.js +19 -0
  96. package/build/models/CreateTransferRequest.d.ts +91 -0
  97. package/build/models/CreateTransferRequest.js +19 -0
  98. package/build/models/CreateWithdrawalRequest.d.ts +99 -0
  99. package/build/models/CreateWithdrawalRequest.js +19 -0
  100. package/build/models/DaaUserContext.d.ts +96 -0
  101. package/build/models/DaaUserContext.js +133 -0
  102. package/build/models/Deposit.d.ts +241 -0
  103. package/build/models/Deposit.js +149 -0
  104. package/build/models/DepositSummary.d.ts +91 -0
  105. package/build/models/DepositSummary.js +114 -0
  106. package/build/models/FiatAccount.d.ts +99 -0
  107. package/build/models/FiatAccount.js +151 -0
  108. package/build/models/GenerateAddressRequest.d.ts +67 -0
  109. package/build/models/GenerateAddressRequest.js +68 -0
  110. package/build/models/Money.d.ts +76 -0
  111. package/build/models/Money.js +99 -0
  112. package/build/models/Page.d.ts +33 -0
  113. package/build/models/Page.js +57 -0
  114. package/build/models/PendingDeviceRegistration.d.ts +90 -0
  115. package/build/models/PendingDeviceRegistration.js +180 -0
  116. package/build/models/PreparedSocialLogin.d.ts +155 -0
  117. package/build/models/PreparedSocialLogin.js +235 -0
  118. package/build/models/Transaction.d.ts +187 -0
  119. package/build/models/Transaction.js +134 -0
  120. package/build/models/Transfer.d.ts +335 -0
  121. package/build/models/Transfer.js +240 -0
  122. package/build/models/Wire.d.ts +213 -0
  123. package/build/models/Wire.js +264 -0
  124. package/build/models/Withdrawal.d.ts +201 -0
  125. package/build/models/Withdrawal.js +156 -0
  126. package/build/models/redaction.d.ts +18 -0
  127. package/build/models/redaction.js +23 -0
  128. package/build/sca/ScaClient.d.ts +105 -0
  129. package/build/sca/ScaClient.js +193 -0
  130. package/build/securekey/InMemorySecureKey.d.ts +23 -0
  131. package/build/securekey/InMemorySecureKey.js +127 -0
  132. package/build/securekey/NativeSecureKey.d.ts +24 -0
  133. package/build/securekey/NativeSecureKey.js +178 -0
  134. package/build/securekey/NativeSecureKeyBridge.d.ts +83 -0
  135. package/build/securekey/NativeSecureKeyBridge.js +19 -0
  136. package/build/securekey/SecureKey.d.ts +137 -0
  137. package/build/securekey/SecureKey.js +19 -0
  138. package/build/securekey/alias.d.ts +88 -0
  139. package/build/securekey/alias.js +175 -0
  140. package/build/securekey/ownerAuthKeyResolver.d.ts +56 -0
  141. package/build/securekey/ownerAuthKeyResolver.js +63 -0
  142. package/build/securekey/resolveNativeBridge.d.ts +30 -0
  143. package/build/securekey/resolveNativeBridge.js +120 -0
  144. package/build/testing.d.ts +18 -0
  145. package/build/testing.js +34 -0
  146. package/build/transport/DaaTransport.d.ts +35 -0
  147. package/build/transport/DaaTransport.js +19 -0
  148. package/build/transport/headers.d.ts +30 -0
  149. package/build/transport/headers.js +45 -0
  150. package/build/validation/requestBody.d.ts +27 -0
  151. package/build/validation/requestBody.js +56 -0
  152. package/build/validation/uuid.d.ts +25 -0
  153. package/build/validation/uuid.js +33 -0
  154. package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
  155. package/build/wire/accountLimitsUsagePayload.js +130 -0
  156. package/build/wire/accountPayload.d.ts +36 -0
  157. package/build/wire/accountPayload.js +100 -0
  158. package/build/wire/achPayload.d.ts +24 -0
  159. package/build/wire/achPayload.js +82 -0
  160. package/build/wire/addressObjectPayload.d.ts +44 -0
  161. package/build/wire/addressObjectPayload.js +64 -0
  162. package/build/wire/daaStatusCodes.d.ts +64 -0
  163. package/build/wire/daaStatusCodes.js +69 -0
  164. package/build/wire/dataEnvelope.d.ts +40 -0
  165. package/build/wire/dataEnvelope.js +79 -0
  166. package/build/wire/depositPayload.d.ts +42 -0
  167. package/build/wire/depositPayload.js +159 -0
  168. package/build/wire/deviceContextPayload.d.ts +33 -0
  169. package/build/wire/deviceContextPayload.js +57 -0
  170. package/build/wire/deviceRegistrationResultPayload.d.ts +32 -0
  171. package/build/wire/deviceRegistrationResultPayload.js +128 -0
  172. package/build/wire/errorEnvelope.d.ts +43 -0
  173. package/build/wire/errorEnvelope.js +85 -0
  174. package/build/wire/fiatAccountPayload.d.ts +37 -0
  175. package/build/wire/fiatAccountPayload.js +93 -0
  176. package/build/wire/instant.d.ts +27 -0
  177. package/build/wire/instant.js +91 -0
  178. package/build/wire/jsonNumber.d.ts +30 -0
  179. package/build/wire/jsonNumber.js +34 -0
  180. package/build/wire/moneyPayload.d.ts +30 -0
  181. package/build/wire/moneyPayload.js +56 -0
  182. package/build/wire/paginationLinks.d.ts +28 -0
  183. package/build/wire/paginationLinks.js +167 -0
  184. package/build/wire/payload.d.ts +60 -0
  185. package/build/wire/payload.js +121 -0
  186. package/build/wire/pendingRegistrationPayload.d.ts +32 -0
  187. package/build/wire/pendingRegistrationPayload.js +54 -0
  188. package/build/wire/socialLoginRequestPayload.d.ts +31 -0
  189. package/build/wire/socialLoginRequestPayload.js +72 -0
  190. package/build/wire/transactionPayload.d.ts +31 -0
  191. package/build/wire/transactionPayload.js +126 -0
  192. package/build/wire/transferPayload.d.ts +43 -0
  193. package/build/wire/transferPayload.js +218 -0
  194. package/build/wire/wireEnums.d.ts +22 -0
  195. package/build/wire/wireEnums.js +69 -0
  196. package/build/wire/wirePayload.d.ts +29 -0
  197. package/build/wire/wirePayload.js +138 -0
  198. package/build/wire/withdrawalPayload.d.ts +27 -0
  199. package/build/wire/withdrawalPayload.js +179 -0
  200. package/expo-module.config.json +14 -0
  201. package/ios/DaaRegistrationExceptions.swift +58 -0
  202. package/ios/DaaRegistrationModule.swift +143 -0
  203. package/ios/DaaScaExceptions.swift +96 -0
  204. package/ios/DaaScaModule.swift +125 -0
  205. package/ios/DaaSecureKeyExceptions.swift +77 -0
  206. package/ios/DaaSecureKeyModule.swift +162 -0
  207. package/ios/InstallationIdentityStore.swift +126 -0
  208. package/ios/UnpaddedBase64URL.swift +42 -0
  209. package/package.json +114 -4
  210. package/src/DaaClient.ts +171 -0
  211. package/src/api/AccountLimitsClient.ts +146 -0
  212. package/src/api/AccountsClient.ts +305 -0
  213. package/src/api/AchFiatAccountsClient.ts +147 -0
  214. package/src/api/AuthClient.ts +331 -0
  215. package/src/api/DaaUserClient.ts +270 -0
  216. package/src/api/DepositAddressesClient.ts +239 -0
  217. package/src/api/DepositsClient.ts +208 -0
  218. package/src/api/FiatAccountsClient.ts +50 -0
  219. package/src/api/TransactionsClient.ts +137 -0
  220. package/src/api/TransfersClient.ts +361 -0
  221. package/src/api/WireFiatAccountsClient.ts +172 -0
  222. package/src/api/WithdrawalsClient.ts +339 -0
  223. package/src/api/loginFailure.ts +75 -0
  224. package/src/api/pagination.ts +63 -0
  225. package/src/api/queryParameters.ts +82 -0
  226. package/src/api/resourceRequest.ts +135 -0
  227. package/src/api/signedResource.ts +267 -0
  228. package/src/auth/RegistrationFlowKey.ts +274 -0
  229. package/src/auth/daaRegistrationNative.ts +236 -0
  230. package/src/auth/deviceAuthorization.ts +302 -0
  231. package/src/auth/ownerGrant.ts +102 -0
  232. package/src/auth/prepareReceipt.ts +522 -0
  233. package/src/auth/registrationAuthorization.ts +306 -0
  234. package/src/auth/registrationCodeVerifier.ts +76 -0
  235. package/src/config.ts +156 -0
  236. package/src/crypto/base64url.ts +88 -0
  237. package/src/crypto/bytes.ts +30 -0
  238. package/src/crypto/es256Jws.ts +240 -0
  239. package/src/crypto/jwkThumbprint.ts +65 -0
  240. package/src/crypto/random.ts +113 -0
  241. package/src/crypto/serialization.ts +42 -0
  242. package/src/crypto/sha256.ts +105 -0
  243. package/src/errors.ts +319 -0
  244. package/src/index.ts +223 -0
  245. package/src/models/Account.ts +264 -0
  246. package/src/models/AccountLimitsUsage.ts +192 -0
  247. package/src/models/Ach.ts +269 -0
  248. package/src/models/AddressObject.ts +169 -0
  249. package/src/models/BusinessPii.ts +154 -0
  250. package/src/models/CreateAccountRequest.ts +109 -0
  251. package/src/models/CreateTransferRequest.ts +114 -0
  252. package/src/models/CreateWithdrawalRequest.ts +120 -0
  253. package/src/models/DaaUserContext.ts +172 -0
  254. package/src/models/Deposit.ts +307 -0
  255. package/src/models/DepositSummary.ts +142 -0
  256. package/src/models/FiatAccount.ts +195 -0
  257. package/src/models/GenerateAddressRequest.ts +101 -0
  258. package/src/models/Money.ts +91 -0
  259. package/src/models/Page.ts +48 -0
  260. package/src/models/PendingDeviceRegistration.ts +197 -0
  261. package/src/models/PreparedSocialLogin.ts +287 -0
  262. package/src/models/Transaction.ts +247 -0
  263. package/src/models/Transfer.ts +459 -0
  264. package/src/models/Wire.ts +405 -0
  265. package/src/models/Withdrawal.ts +283 -0
  266. package/src/models/redaction.ts +22 -0
  267. package/src/sca/ScaClient.ts +289 -0
  268. package/src/securekey/InMemorySecureKey.ts +138 -0
  269. package/src/securekey/NativeSecureKey.ts +179 -0
  270. package/src/securekey/NativeSecureKeyBridge.ts +109 -0
  271. package/src/securekey/SecureKey.ts +149 -0
  272. package/src/securekey/alias.ts +204 -0
  273. package/src/securekey/ownerAuthKeyResolver.ts +96 -0
  274. package/src/securekey/resolveNativeBridge.ts +185 -0
  275. package/src/testing.ts +32 -0
  276. package/src/transport/DaaTransport.ts +42 -0
  277. package/src/transport/headers.ts +46 -0
  278. package/src/validation/requestBody.ts +60 -0
  279. package/src/validation/uuid.ts +31 -0
  280. package/src/wire/accountLimitsUsagePayload.ts +182 -0
  281. package/src/wire/accountPayload.ts +108 -0
  282. package/src/wire/achPayload.ts +98 -0
  283. package/src/wire/addressObjectPayload.ts +64 -0
  284. package/src/wire/daaStatusCodes.ts +69 -0
  285. package/src/wire/dataEnvelope.ts +80 -0
  286. package/src/wire/depositPayload.ts +186 -0
  287. package/src/wire/deviceContextPayload.ts +58 -0
  288. package/src/wire/deviceRegistrationResultPayload.ts +153 -0
  289. package/src/wire/errorEnvelope.ts +87 -0
  290. package/src/wire/fiatAccountPayload.ts +112 -0
  291. package/src/wire/instant.ts +93 -0
  292. package/src/wire/jsonNumber.ts +33 -0
  293. package/src/wire/moneyPayload.ts +55 -0
  294. package/src/wire/paginationLinks.ts +204 -0
  295. package/src/wire/payload.ts +146 -0
  296. package/src/wire/pendingRegistrationPayload.ts +75 -0
  297. package/src/wire/socialLoginRequestPayload.ts +89 -0
  298. package/src/wire/transactionPayload.ts +145 -0
  299. package/src/wire/transferPayload.ts +249 -0
  300. package/src/wire/wireEnums.ts +74 -0
  301. package/src/wire/wirePayload.ts +160 -0
  302. package/src/wire/withdrawalPayload.ts +219 -0
  303. package/testing.d.ts +19 -0
  304. package/testing.js +25 -0
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // Signed public POST/GET: either serialize-once body bytes, or no body at all,
20
+ // plus a fresh `X-Device-Authorization` compact JWS.
21
+ //
22
+ // Signed v1 operations carry `query = null`. Failures are classified on the
23
+ // numeric DAA status code only, through `wire/daaStatusCodes.ts`.
24
+ // An invalid, missing, replayed, or mismatched authorization becomes
25
+ // `contract_violation`. A `409` whose body carries `IDEMPOTENCY_KEY_REUSED`
26
+ // (`420034`) becomes `idempotency_conflict`, with the key recovered from the
27
+ // same request bytes that were signed and sent, not the (unsigned) response
28
+ // body; the caller reconciles the original operation rather than replacing the
29
+ // key.
30
+ //
31
+ // DAA has no code for an expired device authorization, a missing one, or a
32
+ // revoked credential: it reports them as `DEVICE_AUTHORIZATION_INVALID` or,
33
+ // on context refresh, `DEVICE_AUTHORIZATION_REQUEST_MISMATCH`, and the SDK
34
+ // classifies the code it receives. So a signed call is sent once, with no
35
+ // fresh-JWS retry, and no DAA response produces `device_revoked`. A
36
+ // non-numeric string `code` is `api`, even when it is the name of one of these
37
+ // conditions or of a row this mapping classifies.
38
+ //
39
+ // `AccountsClient.create` (`create_account`),
40
+ // `TransfersClient.create` (`transfer`), and `WithdrawalsClient.create`
41
+ // (`withdrawal`) call `postSignedResource`. `DaaUserClient.refreshContext`
42
+ // (`get_device_context`) calls `getSignedResource` — the device-authorization
43
+ // contract treats "signed context refresh" alongside protected writes, and
44
+ // `securekey/SecureKey.ts` lists it alongside them as one of the defined DAA
45
+ // operations signing is reachable for.
46
+
47
+ import {
48
+ authorizeExactRequest,
49
+ DEVICE_AUTHORIZATION_HEADER,
50
+ deviceAuthorizationProfile,
51
+ idempotencyKeyFromExactBody,
52
+ type DeviceAuthorizationOperation,
53
+ } from '../auth/deviceAuthorization'
54
+ import { apiFailure, contractViolation, idempotencyConflict, type DaaError } from '../errors'
55
+ import type { OwnerAuthKeyResolver } from '../securekey/ownerAuthKeyResolver'
56
+ import type { OwnerAuthKey } from '../securekey/SecureKey'
57
+ import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
58
+ import { headerValueIgnoringCase } from '../transport/headers'
59
+ import { isDaaStatus } from '../wire/daaStatusCodes'
60
+ import { readDaaStatusCode } from '../wire/errorEnvelope'
61
+ import { decodeResourceResponse } from './resourceRequest'
62
+
63
+ /**
64
+ * What a resource client needs to authorize a signed write: the same pair
65
+ * `postSignedResource` takes, except the key is resolved when a write is
66
+ * actually made rather than held from the moment `forUser` returns.
67
+ *
68
+ * The two halves come from the same `ACTIVE` Device Registration Complete.
69
+ * `authKeyId` is the `DeviceContext` value the service assigned; the key itself
70
+ * is enclave-held and is not a field on that decoded result, so it is
71
+ * re-resolved by the `{appId, environment, clientEntityId}` alias login
72
+ * already used.
73
+ *
74
+ * Passed as one required value, because the failure this prevents is
75
+ * `DaaClient.forUser` validating a user context and then building the
76
+ * operations surface without it — leaving every write with nothing to sign
77
+ * with. A required constructor parameter makes that omission a compile error.
78
+ *
79
+ * Not on the public entry. A consumer holding one could reach
80
+ * `OwnerAuthKey.signExactBytes`, which is the generic signing surface this SDK
81
+ * deliberately does not expose.
82
+ */
83
+ export type DaaUserSigning = Readonly<{
84
+ /** Resolves the installation AuthKey. Signing fails closed until it is registered. */
85
+ resolveAuthKey: OwnerAuthKeyResolver
86
+ /** `DeviceContext.authKeyId`, which becomes the authorization JWS `kid`. */
87
+ authKeyId: string
88
+ }>
89
+
90
+ export type PostSignedResourceOptions<T> = Readonly<{
91
+ transport: DaaTransport
92
+ operation: DeviceAuthorizationOperation
93
+ authKey: OwnerAuthKey
94
+ authKeyId: string
95
+ /** Final serialized bytes. Hashed and sent as this same slice. */
96
+ bodyBytes: Uint8Array
97
+ expectedStatus: number
98
+ decode: (value: unknown) => T
99
+ }>
100
+
101
+ /** Execute a public POST with a fresh registered-device authorization header. */
102
+ export async function postSignedResource<T>({
103
+ transport,
104
+ operation,
105
+ authKey,
106
+ authKeyId,
107
+ bodyBytes,
108
+ expectedStatus,
109
+ decode,
110
+ }: PostSignedResourceOptions<T>): Promise<T> {
111
+ const profile = deviceAuthorizationProfile(operation)
112
+ if (profile.method !== 'POST') {
113
+ throw contractViolation('postSignedResource only sends POST registry operations')
114
+ }
115
+
116
+ const response = await sendSignedPost({
117
+ transport,
118
+ operation,
119
+ path: profile.canonicalPath,
120
+ authKey,
121
+ authKeyId,
122
+ bodyBytes,
123
+ })
124
+
125
+ if (response.status !== expectedStatus) {
126
+ throw mapSignedRequestFailure(response, bodyBytes)
127
+ }
128
+ return decodeResourceResponse({ response, expectedStatus, decode })
129
+ }
130
+
131
+ export type GetSignedResourceOptions<T> = Readonly<{
132
+ transport: DaaTransport
133
+ operation: DeviceAuthorizationOperation
134
+ authKey: OwnerAuthKey
135
+ authKeyId: string
136
+ expectedStatus: number
137
+ decode: (value: unknown) => T
138
+ }>
139
+
140
+ /** No body to serialize for a bodyless signed read; the signature hashes the empty byte array. */
141
+ const EMPTY_BODY = new Uint8Array(0)
142
+
143
+ /**
144
+ * Execute a public GET with a fresh registered-device authorization header.
145
+ *
146
+ * The only registry operation this reaches is `get_device_context`
147
+ * (`DaaUserClient.refreshContext`). There is no request body to serialize or
148
+ * sign over: `authorizeExactRequest` hashes the empty byte array per the
149
+ * bodyless-request rule, and nothing is sent as a request entity — the same
150
+ * bodyless shape `resourceRequest.ts`'s unsigned `readResource` sends.
151
+ */
152
+ export async function getSignedResource<T>({
153
+ transport,
154
+ operation,
155
+ authKey,
156
+ authKeyId,
157
+ expectedStatus,
158
+ decode,
159
+ }: GetSignedResourceOptions<T>): Promise<T> {
160
+ const profile = deviceAuthorizationProfile(operation)
161
+ if (profile.method !== 'GET') {
162
+ throw contractViolation('getSignedResource only sends GET registry operations')
163
+ }
164
+
165
+ const response = await sendSignedGet({
166
+ transport,
167
+ operation,
168
+ path: profile.canonicalPath,
169
+ authKey,
170
+ authKeyId,
171
+ })
172
+
173
+ if (response.status !== expectedStatus) {
174
+ throw mapSignedRequestFailure(response, EMPTY_BODY)
175
+ }
176
+ return decodeResourceResponse({ response, expectedStatus, decode })
177
+ }
178
+
179
+ async function sendSignedGet(args: {
180
+ transport: DaaTransport
181
+ operation: DeviceAuthorizationOperation
182
+ path: string
183
+ authKey: OwnerAuthKey
184
+ authKeyId: string
185
+ }): Promise<DaaHttpResponse> {
186
+ const compactJws = await authorizeExactRequest({
187
+ authKey: args.authKey,
188
+ authKeyId: args.authKeyId,
189
+ operation: args.operation,
190
+ bodyBytes: EMPTY_BODY,
191
+ })
192
+ return args.transport.send({
193
+ method: 'GET',
194
+ path: args.path,
195
+ query: null,
196
+ headers: {
197
+ [DEVICE_AUTHORIZATION_HEADER]: compactJws,
198
+ },
199
+ bodyBytes: null,
200
+ })
201
+ }
202
+
203
+ async function sendSignedPost(args: {
204
+ transport: DaaTransport
205
+ operation: DeviceAuthorizationOperation
206
+ path: string
207
+ authKey: OwnerAuthKey
208
+ authKeyId: string
209
+ bodyBytes: Uint8Array
210
+ }): Promise<DaaHttpResponse> {
211
+ const compactJws = await authorizeExactRequest({
212
+ authKey: args.authKey,
213
+ authKeyId: args.authKeyId,
214
+ operation: args.operation,
215
+ bodyBytes: args.bodyBytes,
216
+ })
217
+ return args.transport.send({
218
+ method: 'POST',
219
+ path: args.path,
220
+ query: null,
221
+ headers: {
222
+ 'Content-Type': 'application/json',
223
+ [DEVICE_AUTHORIZATION_HEADER]: compactJws,
224
+ },
225
+ bodyBytes: args.bodyBytes,
226
+ })
227
+ }
228
+
229
+ function mapSignedRequestFailure(response: DaaHttpResponse, bodyBytes: Uint8Array): DaaError {
230
+ const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
231
+ const daaStatusCode = readDaaStatusCode(response.bodyBytes)
232
+ const fallback = (): DaaError =>
233
+ apiFailure({
234
+ httpStatus: response.status,
235
+ daaStatusCode,
236
+ correlationId,
237
+ })
238
+ if (isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) {
239
+ // Gated on both the status code and the HTTP status, so a body that
240
+ // carries this code on some other status falls through to the generic
241
+ // `api` failure below rather than being trusted. The contract puts this
242
+ // code at `409`, which is where DAA's transfer and withdrawal
243
+ // create routes send it. Non-custodial account create never sends it (a
244
+ // reused key returns the original account). Recovered from the signed
245
+ // request's own bytes, not the response — `idempotencyKeyFromExactBody`
246
+ // returns `undefined` for a bodyless request (`getSignedResource`), so this
247
+ // never fires for `get_device_context`.
248
+ const idempotencyKey =
249
+ response.status === 409 ? idempotencyKeyFromExactBody(bodyBytes) : undefined
250
+ return idempotencyKey !== undefined
251
+ ? idempotencyConflict(idempotencyKey, correlationId)
252
+ : fallback()
253
+ }
254
+ if (
255
+ isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REPLAYED') ||
256
+ isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REQUEST_MISMATCH')
257
+ ) {
258
+ return contractViolation(
259
+ 'the device authorization was replayed or did not match the request',
260
+ correlationId,
261
+ )
262
+ }
263
+ if (isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_INVALID')) {
264
+ return contractViolation('the device authorization was rejected', correlationId)
265
+ }
266
+ return fallback()
267
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // The ephemeral registration-flow key.
20
+ //
21
+ // ============================================================================
22
+ // THIS IS NOT AN AuthKey. Do not treat it as one, and do not route it through
23
+ // `SecureKeyStore`.
24
+ // ============================================================================
25
+ //
26
+ // The login contract uses two different P-256 keys, and confusing
27
+ // them is the failure this file's naming exists to prevent:
28
+ //
29
+ // | | AuthKey (`OwnerAuthKey`, `securekey/`) | registration-flow key (this file) |
30
+ // | --- | --- | --- |
31
+ // | Lifetime | durable, survives the app | **one login attempt** |
32
+ // | Scope | `{environment, customer application, Owner (clientEntityId), installation}` | nothing; it is anonymous |
33
+ // | Storage | Secure Enclave / Android Keystore, via `SecureKeyStore` | process memory only |
34
+ // | Exported at | Device Registration Complete (`authKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) |
35
+ // | Selected | only *after* the Social Session response | before Prepare |
36
+ // | Authorizes | DAA operations, via `X-Device-Authorization` | nothing |
37
+ //
38
+ // The contract says the same thing in one line on
39
+ // `PrepareSocialLoginRequest.registrationFlowPublicKey`: "Unpadded Base64URL DER
40
+ // SubjectPublicKeyInfo for an ephemeral P-256 flow key; **it is not an AuthKey**".
41
+ //
42
+ // Its whole job is to prove, at Device Registration Complete, that the caller
43
+ // completing the registration is the caller that prepared it — the flow-key JWS
44
+ // is one of the two fresh proofs over the exact Complete request bytes. Because
45
+ // it is per-attempt and anonymous, it deliberately does NOT go into the
46
+ // enclave: a key in the Secure Enclave is a key that outlives the attempt and
47
+ // acquires a namespace, which is exactly what this one must not have.
48
+ //
49
+ // Signing is a **typed Complete-only helper**, not a public `sign(bytes)`. The
50
+ // member is `signExactBytes` of the JWS signing input for
51
+ // `X-Registration-Flow-Authorization`. It is not exported from `index.ts`.
52
+ // Both the native Expo bridge (`DaaRegistrationFlowKey.signRegistrationAuthorization`
53
+ // on iOS and Android) and the WebCrypto test stand-in sign for real, so Device
54
+ // Registration Complete can finish on a physical device.
55
+
56
+ import { fromBase64Url, toBase64Url } from '../crypto/base64url'
57
+ import { toArrayBuffer } from '../crypto/bytes'
58
+ import { contractViolation } from '../errors'
59
+ import {
60
+ nativeGenerateRegistrationFlowKey,
61
+ nativeRegistrationFlowPublicKeySpkiBase64Url,
62
+ nativeReleaseRegistrationFlowKey,
63
+ nativeSignRegistrationAuthorization,
64
+ requireDaaRegistrationNative,
65
+ type DaaRegistrationNativeModule,
66
+ } from './daaRegistrationNative'
67
+
68
+ /** Byte length of a P-256 SubjectPublicKeyInfo. */
69
+ const P256_SPKI_BYTE_LENGTH = 91
70
+
71
+ /**
72
+ * One attempt's registration-flow key. Not an AuthKey; see the file header.
73
+ *
74
+ * The interface carries the public-key export for Prepare, the Complete-only
75
+ * signing helper, and an explicit release: the native implementations hold the
76
+ * private key in a process-lifetime cache, so something has to say when it is
77
+ * no longer needed.
78
+ */
79
+ export interface RegistrationFlowKey {
80
+ /**
81
+ * Unpadded Base64URL DER SubjectPublicKeyInfo of the public key, the exact
82
+ * form `PrepareSocialLoginRequest.registrationFlowPublicKey` wants.
83
+ */
84
+ publicKeySpkiBase64Url(): Promise<string>
85
+
86
+ /**
87
+ * ES256 signature (JOSE `R || S`, 64 bytes) over the exact Device Registration
88
+ * Complete flow-JWS signing input. Not a public generic sign API.
89
+ */
90
+ signExactBytes(message: Uint8Array): Promise<Uint8Array>
91
+
92
+ /**
93
+ * Discard the key, so a native implementation stops holding its private half.
94
+ *
95
+ * Safe to call more than once and safe to call on a key that was never used.
96
+ * The key is dead afterwards: `publicKeySpkiBase64Url()` on a released native
97
+ * key fails closed rather than returning a stale value.
98
+ *
99
+ * Device Registration Complete is the owner of this call: it signs, then
100
+ * releases. `PreparedSocialLogin.abandon()` is the other caller when the user
101
+ * backs out of provider login. `PendingDeviceRegistration` has no
102
+ * `abandon()`: after Session, the key is held until Complete or until the
103
+ * process exits.
104
+ */
105
+ release(): Promise<void>
106
+ }
107
+
108
+ /**
109
+ * Source of per-attempt registration-flow keys.
110
+ *
111
+ * A seam so `AuthClient` can switch providers without changing callers.
112
+ * Production generation is `DaaRegistrationFlowKey` in `daa-ios-sdk` /
113
+ * `daa-android-sdk` — not `DaaSecureKey`, which is the Owner AuthKey. The Expo
114
+ * `DaaRegistration` module bridges that type and keeps the private key in
115
+ * native memory. WebCrypto is an explicit test stand-in
116
+ * (`webCryptoRegistrationFlowKeyProvider`), never a fallback. A host missing
117
+ * the Expo module fails closed. The seam is not exported from `index.ts`: a
118
+ * consumer cannot substitute the key that proves its own registration handoff.
119
+ */
120
+ export interface RegistrationFlowKeyProvider {
121
+ generate(): Promise<RegistrationFlowKey>
122
+ }
123
+
124
+ class WebCryptoRegistrationFlowKey implements RegistrationFlowKey {
125
+ readonly #keyPair: CryptoKeyPair
126
+
127
+ constructor(keyPair: CryptoKeyPair) {
128
+ this.#keyPair = keyPair
129
+ Object.freeze(this)
130
+ }
131
+
132
+ // Nothing to free: the CryptoKey is ordinary garbage once the handle is
133
+ // dropped, and WebCrypto exposes no destroy. Present so the two providers
134
+ // satisfy one interface.
135
+ async release(): Promise<void> {}
136
+
137
+ async publicKeySpkiBase64Url(): Promise<string> {
138
+ const spki = await subtle().exportKey('spki', this.#keyPair.publicKey)
139
+ const bytes = new Uint8Array(spki)
140
+ if (bytes.length !== P256_SPKI_BYTE_LENGTH) {
141
+ throw contractViolation(
142
+ 'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo',
143
+ )
144
+ }
145
+ return toBase64Url(bytes)
146
+ }
147
+
148
+ async signExactBytes(message: Uint8Array): Promise<Uint8Array> {
149
+ const signature = await subtle().sign(
150
+ { name: 'ECDSA', hash: 'SHA-256' },
151
+ this.#keyPair.privateKey,
152
+ toArrayBuffer(message),
153
+ )
154
+ return new Uint8Array(signature)
155
+ }
156
+ }
157
+
158
+ class NativeRegistrationFlowKey implements RegistrationFlowKey {
159
+ readonly #native: DaaRegistrationNativeModule
160
+ readonly #id: string
161
+
162
+ constructor(native: DaaRegistrationNativeModule, id: string) {
163
+ this.#native = native
164
+ this.#id = id
165
+ Object.freeze(this)
166
+ }
167
+
168
+ async publicKeySpkiBase64Url(): Promise<string> {
169
+ const spki = nativeRegistrationFlowPublicKeySpkiBase64Url(this.#native, this.#id)
170
+ const bytes = decodeSpki(spki)
171
+ return toBase64Url(bytes)
172
+ }
173
+
174
+ async release(): Promise<void> {
175
+ nativeReleaseRegistrationFlowKey(this.#native, this.#id)
176
+ }
177
+
178
+ async signExactBytes(message: Uint8Array): Promise<Uint8Array> {
179
+ // The Expo module holds the private key; only the exact bytes and the
180
+ // resulting signature cross the bridge as Base64URL strings.
181
+ const signingInputBase64Url = toBase64Url(message)
182
+ return nativeSignRegistrationAuthorization(this.#native, this.#id, signingInputBase64Url)
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Production React Native provider: native `DaaRegistrationFlowKey` via the
188
+ * Expo `DaaRegistration` module. The private key never crosses the bridge.
189
+ */
190
+ export function nativeRegistrationFlowKeyProvider(
191
+ native: DaaRegistrationNativeModule,
192
+ ): RegistrationFlowKeyProvider {
193
+ return {
194
+ async generate(): Promise<RegistrationFlowKey> {
195
+ const id = nativeGenerateRegistrationFlowKey(native)
196
+ return new NativeRegistrationFlowKey(native, id)
197
+ },
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Node/Jest stand-in: a non-extractable WebCrypto P-256 keypair per attempt.
203
+ *
204
+ * `extractable: false` is set even though the key never leaves the process. It
205
+ * costs nothing, and it means a future bug that hands the handle somewhere else
206
+ * still cannot export the private key.
207
+ *
208
+ * **Not the production RN path.** Production `defaultRegistrationFlowKeyProvider`
209
+ * never calls this. Absent `crypto.subtle`, `generate()` fails closed with
210
+ * `contract_violation` rather than weaker key generation.
211
+ */
212
+ export function webCryptoRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider {
213
+ return {
214
+ async generate(): Promise<RegistrationFlowKey> {
215
+ const keyPair = (await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [
216
+ 'sign',
217
+ 'verify',
218
+ ])) as CryptoKeyPair
219
+ return new WebCryptoRegistrationFlowKey(keyPair)
220
+ },
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Native `DaaRegistrationFlowKey` via the Expo module. A missing module is a
226
+ * `contract_violation` — WebCrypto is never a fallback. The native module is
227
+ * resolved on `generate()`, not when this provider is constructed, so building
228
+ * a `DaaClient` does not require the Expo module to be linked.
229
+ */
230
+ export function defaultRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider {
231
+ return {
232
+ async generate(): Promise<RegistrationFlowKey> {
233
+ return nativeRegistrationFlowKeyProvider(requireDaaRegistrationNative()).generate()
234
+ },
235
+ }
236
+ }
237
+
238
+ /** Drop the key without replacing the failure that triggered cleanup. */
239
+ export async function releaseQuietly(key: RegistrationFlowKey): Promise<void> {
240
+ try {
241
+ await key.release()
242
+ } catch {
243
+ // Intentionally empty: a throwing release must not mask the originating error.
244
+ }
245
+ }
246
+
247
+ function decodeSpki(spki: string): Uint8Array {
248
+ let bytes: Uint8Array
249
+ try {
250
+ bytes = fromBase64Url(spki)
251
+ } catch {
252
+ throw contractViolation(
253
+ 'registration-flow key did not export valid Base64URL SubjectPublicKeyInfo',
254
+ )
255
+ }
256
+ if (bytes.length !== P256_SPKI_BYTE_LENGTH) {
257
+ throw contractViolation(
258
+ 'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo',
259
+ )
260
+ }
261
+ return bytes
262
+ }
263
+
264
+ function subtle(): SubtleCrypto {
265
+ const host = (globalThis as { crypto?: Crypto }).crypto
266
+ if (host === undefined || host.subtle === undefined) {
267
+ throw contractViolation(
268
+ 'crypto.subtle is required to generate the ephemeral registration-flow key; ' +
269
+ 'install a WebCrypto polyfill in the host app or supply a native ' +
270
+ 'DaaRegistrationFlowKey provider',
271
+ )
272
+ }
273
+ return host.subtle
274
+ }